use serde::{Deserialize, Serialize};
pub use ash_time::{HlcClock, HlcError, HlcTimestamp};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct EventClock {
pub physical: u64,
pub logical: u32,
}
impl EventClock {
#[must_use]
pub fn happened_before(self, other: Self) -> bool {
self < other
}
}
impl From<HlcTimestamp> for EventClock {
fn from(ts: HlcTimestamp) -> Self {
Self {
physical: ts.physical,
logical: ts.logical,
}
}
}
impl From<EventClock> for HlcTimestamp {
fn from(clock: EventClock) -> Self {
Self {
physical: clock.physical,
logical: clock.logical,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_round_trips_through_the_underlying_timestamp() {
let clock = HlcClock::new();
let ts = clock.now().expect("system clock is sane under test");
let stored = EventClock::from(ts);
assert_eq!(HlcTimestamp::from(stored), ts);
}
#[test]
fn test_ordering_matches_the_underlying_timestamp() {
let clock = HlcClock::new();
let first = clock.now().unwrap();
let second = clock.now().unwrap();
assert!(first.happened_before(second));
assert!(EventClock::from(first).happened_before(EventClock::from(second)));
assert!(EventClock::from(first) < EventClock::from(second));
}
#[test]
fn test_serializes_as_two_named_fields() {
let clock = EventClock {
physical: 1_700_000_000_000_000_000,
logical: 7,
};
let json = serde_json::to_value(clock).unwrap();
assert_eq!(json["physical"], 1_700_000_000_000_000_000_u64);
assert_eq!(json["logical"], 7);
let back: EventClock = serde_json::from_value(json).unwrap();
assert_eq!(back, clock);
}
#[test]
fn test_logical_counter_breaks_ties_within_a_nanosecond() {
let earlier = EventClock {
physical: 42,
logical: 0,
};
let later = EventClock {
physical: 42,
logical: 1,
};
assert!(earlier.happened_before(later));
assert!(!later.happened_before(earlier));
}
}