Skip to main content

cbcl_core/
hlc.rs

1//! SPEC-035 ADR-3502: immutable, host-supplied hybrid logical clock evidence.
2//!
3//! Advancement cases follow Kulkarni et al., Logical Physical Clocks (2014),
4//! https://cse.buffalo.edu/tech-reports/2014-04.pdf, section 3. CBCL adds
5//! fixed-width u64/u32 evidence and checked overflow refusal.
6//!
7//! This module reads no clock and performs no IO. Hosts supply physical milliseconds,
8//! merge observed timestamps and durably retain the returned value. Recognition proves
9//! canonical syntax, not honest clock generation or Byzantine ordering/finality.
10#![forbid(unsafe_code)]
11use alloc::format;
12use alloc::string::String;
13
14/// Fixed canonical spelling: `hlc-` + 16 lowercase hex + `-` + 8 lowercase hex.
15pub const WIRE_LEN: usize = 29;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
18pub struct Hlc {
19    pub physical_ms: u64,
20    pub logical: u32,
21}
22
23impl Hlc {
24    pub const fn new(physical_ms: u64, logical: u32) -> Self {
25        Self {
26            physical_ms,
27            logical,
28        }
29    }
30
31    /// Full recognition, including width, separators and lowercase canonical form.
32    pub fn parse(text: &str) -> Option<Self> {
33        let bytes = text.as_bytes();
34        if bytes.len() != WIRE_LEN || !bytes.starts_with(b"hlc-") || bytes[20] != b'-' {
35            return None;
36        }
37        let lower_hex = |b: &u8| b.is_ascii_digit() || (b'a'..=b'f').contains(b);
38        if !bytes[4..20].iter().all(lower_hex) || !bytes[21..29].iter().all(lower_hex) {
39            return None;
40        }
41        Some(Self::new(
42            u64::from_str_radix(&text[4..20], 16).ok()?,
43            u32::from_str_radix(&text[21..29], 16).ok()?,
44        ))
45    }
46
47    pub fn render(self) -> String {
48        format!("hlc-{:016x}-{:08x}", self.physical_ms, self.logical)
49    }
50
51    /// Advance for a local event or receipt of remote evidence. Overflow refuses
52    /// issuance; it never wraps or silently moves physical time into the future.
53    pub fn advance(self, now_ms: u64, remote: Option<Self>) -> Option<Self> {
54        let physical = self
55            .physical_ms
56            .max(now_ms)
57            .max(remote.map_or(0, |r| r.physical_ms));
58        let logical = match remote {
59            Some(r) if physical == self.physical_ms && physical == r.physical_ms => {
60                self.logical.max(r.logical).checked_add(1)?
61            }
62            _ if physical == self.physical_ms => self.logical.checked_add(1)?,
63            Some(r) if physical == r.physical_ms => r.logical.checked_add(1)?,
64            _ => 0,
65        };
66        Some(Self::new(physical, logical))
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    #[test]
74    fn canonical_recognition_and_roundtrip() {
75        for stamp in [
76            Hlc::new(0, 0),
77            Hlc::new(1_800_000_000_000, 42),
78            Hlc::new(u64::MAX, u32::MAX),
79        ] {
80            assert_eq!(Hlc::parse(&stamp.render()), Some(stamp));
81        }
82        for invalid in [
83            "",
84            "hlc-1-0",
85            "hlc-000000000000000A-00000000",
86            "hlc-0000000000000000-000000000",
87            "hlc-0000000000000000-0000000g",
88            "hlc-0000000000000000-00000000x",
89            "hlc-000000000000000é-00000000",
90        ] {
91            assert_eq!(Hlc::parse(invalid), None, "{invalid}");
92        }
93    }
94    #[test]
95    fn advance_handles_skew_receipt_ties_restart_and_overflow() {
96        let own = Hlc::new(100, 4);
97        assert_eq!(own.advance(99, None), Some(Hlc::new(100, 5)));
98        assert_eq!(own.advance(101, None), Some(Hlc::new(101, 0)));
99        assert_eq!(
100            own.advance(99, Some(Hlc::new(100, 9))),
101            Some(Hlc::new(100, 10))
102        );
103        assert_eq!(
104            own.advance(99, Some(Hlc::new(102, 3))),
105            Some(Hlc::new(102, 4))
106        );
107        assert_eq!(
108            own.advance(103, Some(Hlc::new(102, 3))),
109            Some(Hlc::new(103, 0))
110        );
111        let restored = Hlc::parse(&own.render()).unwrap();
112        assert!(restored.advance(1, None).unwrap() > own);
113        assert_eq!(Hlc::new(100, u32::MAX).advance(99, None), None);
114        assert_eq!(own.advance(1, Some(Hlc::new(200, u32::MAX))), None);
115        assert_eq!(Hlc::new(u64::MAX, u32::MAX).advance(u64::MAX, None), None);
116    }
117}