Skip to main content

tilo_resource/
clock.rs

1//! A hybrid logical clock: the wall clock moved past every time its holder has
2//! seen, so what it writes reads after what it had already read however far
3//! the machines' clocks are apart.
4//!
5//! What is ordered by when it was written is stamped with one on the origin, and
6//! the action carries the result: every replica reads the same time, and
7//! nothing in `apply` decides it from its own state.
8
9/// A writer's clock over the times it has seen.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub struct HybridClock {
12    latest: Option<i64>,
13}
14
15impl HybridClock {
16    /// A clock that has seen nothing.
17    #[must_use]
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// Take in a time the writer has seen, in milliseconds since the epoch.
23    pub fn see(&mut self, ts: i64) {
24        self.latest = Some(self.latest.map_or(ts, |latest| latest.max(ts)));
25    }
26
27    /// The time to write at: `wall_ms`, or a millisecond after the latest seen
28    /// time when the wall clock is not past it.
29    #[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}