Skip to content

Commit

Permalink
Change NTP64 Display and FromStr impl to use u64 representation inste…
Browse files Browse the repository at this point in the history
…ad of RFC3339
  • Loading branch information
JEnoch committed Jun 27, 2024
1 parent 68bf159 commit 7a78ef0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
26 changes: 9 additions & 17 deletions src/ntp64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use {
core::str::FromStr,
humantime::{format_rfc3339_nanos, parse_rfc3339},
std::time::{SystemTime, UNIX_EPOCH},
};

Expand Down Expand Up @@ -210,16 +209,17 @@ impl SubAssign<u64> for NTP64 {

impl fmt::Display for NTP64 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
#[cfg(feature = "std")]
return write!(f, "{}", format_rfc3339_nanos(self.to_system_time()));
#[cfg(not(feature = "std"))]
return write!(f, "{:x}", self.0);
write!(f, "{}", self.0)
// #[cfg(feature = "std")]
// return write!(f, "{}", format_rfc3339_nanos(self.to_system_time()));
// #[cfg(not(feature = "std"))]
// return write!(f, "{:x}", self.0);
}
}

impl fmt::Debug for NTP64 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:x}", self.0)
write!(f, "{}", self.0)
}
}

Expand All @@ -237,17 +237,9 @@ impl FromStr for NTP64 {
type Err = ParseNTP64Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_rfc3339(s)
.map_err(|e| ParseNTP64Error {
cause: e.to_string(),
})
.and_then(|time| {
time.duration_since(UNIX_EPOCH)
.map_err(|e| ParseNTP64Error {
cause: e.to_string(),
})
})
.map(NTP64::from)
u64::from_str(s).map(NTP64).map_err(|_| ParseNTP64Error {
cause: format!("Invalid NTP64 time : '{s}' (must be a u64)"),
})
}
}

Expand Down
19 changes: 19 additions & 0 deletions src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,23 @@ mod tests {
let diff = ts1_now.get_diff_duration(&ts2_now);
assert_eq!(diff, Duration::from_secs(0));
}

#[test]
fn bijective_string_conversion() {
use crate::*;
use std::convert::TryFrom;
use std::str::FromStr;
let id: ID = ID::try_from([0x01]).unwrap();

for n in 0u64..10000 {
let ts = Timestamp::new(NTP64(n), id);
assert_eq!(ts, Timestamp::from_str(&ts.to_string()).unwrap());
}

let hlc = HLCBuilder::new().with_id(ID::rand()).build();
for _ in 1..1000 {
let now_ts = hlc.new_timestamp();
assert_eq!(now_ts, Timestamp::from_str(&now_ts.to_string()).unwrap());
}
}
}

0 comments on commit 7a78ef0

Please sign in to comment.