1#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub struct HybridClock {
12 latest: Option<i64>,
13}
14
15impl HybridClock {
16 #[must_use]
18 pub fn new() -> Self {
19 Self::default()
20 }
21
22 pub fn see(&mut self, ts: i64) {
24 self.latest = Some(self.latest.map_or(ts, |latest| latest.max(ts)));
25 }
26
27 #[must_use]
30 pub fn stamp(&self, wall_ms: i64) -> i64 {
31 self.latest
32 .map_or(wall_ms, |latest| wall_ms.max(latest.saturating_add(1)))
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::HybridClock;
39
40 #[test]
41 fn a_write_reads_after_what_was_seen_even_when_the_clock_is_behind() {
42 let mut clock = HybridClock::new();
43 assert_eq!(clock.stamp(1_000), 1_000, "nothing seen: the wall clock");
44 clock.see(2_000);
45 assert_eq!(clock.stamp(1_000), 2_001, "a behind clock writes after");
46 assert_eq!(clock.stamp(5_000), 5_000, "an ahead clock writes now");
47 clock.see(9_000);
48 assert_eq!(clock.stamp(5_000), 9_001);
49 clock.see(8_000);
50 assert_eq!(clock.stamp(5_000), 9_001, "the latest seen stands");
51 }
52}