1use std::sync::atomic::{AtomicU64, Ordering};
29use std::time::{SystemTime, UNIX_EPOCH};
30
31use serde::{Deserialize, Serialize};
32
33use crate::named::Named;
34
35#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
44pub struct Instant {
45 pub physical_ms: u64,
47 pub logical: u16,
49}
50
51impl Instant {
52 #[must_use]
54 pub fn new(physical_ms: u64, logical: u16) -> Self {
55 Self {
56 physical_ms,
57 logical,
58 }
59 }
60
61 #[must_use]
63 pub const fn zero() -> Self {
64 Self {
65 physical_ms: 0,
66 logical: 0,
67 }
68 }
69
70 #[must_use]
74 pub const fn from_ms(physical_ms: u64) -> Self {
75 Self {
76 physical_ms,
77 logical: 0,
78 }
79 }
80
81 #[must_use]
84 pub fn to_packed(&self) -> u64 {
85 let phys = self.physical_ms & ((1u64 << 48) - 1);
86 (phys << 16) | u64::from(self.logical)
87 }
88
89 #[must_use]
91 pub fn from_packed(packed: u64) -> Self {
92 let logical = (packed & 0xFFFF) as u16;
93 let physical_ms = packed >> 16;
94 Self {
95 physical_ms,
96 logical,
97 }
98 }
99
100 #[must_use]
102 pub fn to_bytes(&self) -> [u8; 8] {
103 self.to_packed().to_be_bytes()
104 }
105
106 #[must_use]
109 pub fn causally_after(&self, other: &Self) -> bool {
110 (self.physical_ms, self.logical) > (other.physical_ms, other.logical)
111 }
112
113 #[must_use]
119 pub fn tick(now: Self, previous: Self) -> Self {
120 if now.causally_after(&previous) || now == previous {
121 if now == previous {
122 Self {
124 physical_ms: now.physical_ms,
125 logical: now.logical.saturating_add(1),
126 }
127 } else {
128 now
129 }
130 } else {
131 Self {
134 physical_ms: previous.physical_ms,
135 logical: previous.logical.saturating_add(1),
136 }
137 }
138 }
139}
140
141impl PartialOrd for Instant {
142 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
143 Some(self.cmp(other))
144 }
145}
146
147impl Ord for Instant {
148 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
149 (self.physical_ms, self.logical).cmp(&(other.physical_ms, other.logical))
150 }
151}
152
153impl std::fmt::Display for Instant {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 write!(f, "{}.{:05}", self.physical_ms, self.logical)
156 }
157}
158
159crate::impl_fingerprint!(Instant);
160
161pub trait Clock: Named + Send + Sync {
164 fn now(&self) -> Instant;
166
167 fn tick(&self, observed: Instant) -> Instant {
172 let now = self.now();
173 Instant::tick(now.max(observed), observed)
174 }
175
176 fn unix_secs(&self) -> u64 {
180 self.now().physical_ms / 1000
181 }
182
183 fn unix_ms(&self) -> u64 {
186 self.now().physical_ms
187 }
188}
189
190#[derive(Default, Clone, Copy)]
198pub struct WallClock;
199
200crate::define_named!(WallClock, "wall");
201
202impl Clock for WallClock {
203 fn now(&self) -> Instant {
204 let physical_ms = SystemTime::now()
205 .duration_since(UNIX_EPOCH)
206 .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
207 Instant {
208 physical_ms,
209 logical: 0,
210 }
211 }
212}
213
214pub struct FrozenClock {
222 physical_ms: AtomicU64,
223 logical: AtomicU64, }
225
226crate::define_named!(FrozenClock, "frozen");
227
228impl FrozenClock {
229 #[must_use]
231 pub fn at(physical_ms: u64) -> Self {
232 Self {
233 physical_ms: AtomicU64::new(physical_ms),
234 logical: AtomicU64::new(0),
235 }
236 }
237
238 pub fn advance(&self, ms: u64) {
240 self.physical_ms.fetch_add(ms, Ordering::SeqCst);
241 self.logical.store(0, Ordering::SeqCst);
242 }
243
244 pub fn tick_logical(&self) {
246 self.logical.fetch_add(1, Ordering::SeqCst);
247 }
248
249 pub fn reset(&self) {
251 self.physical_ms.store(0, Ordering::SeqCst);
252 self.logical.store(0, Ordering::SeqCst);
253 }
254}
255
256impl Default for FrozenClock {
257 fn default() -> Self {
258 Self::at(0)
259 }
260}
261
262impl Clock for FrozenClock {
263 fn now(&self) -> Instant {
264 Instant {
265 physical_ms: self.physical_ms.load(Ordering::SeqCst),
266 logical: u16::try_from(self.logical.load(Ordering::SeqCst)).unwrap_or(u16::MAX),
267 }
268 }
269}
270
271#[derive(Default)]
280pub struct LogicalClock {
281 counter: AtomicU64,
282}
283
284crate::define_named!(LogicalClock, "logical");
285
286impl LogicalClock {
287 #[must_use]
289 pub fn new() -> Self {
290 Self::default()
291 }
292
293 pub fn peek(&self) -> u64 {
295 self.counter.load(Ordering::SeqCst)
296 }
297}
298
299impl Clock for LogicalClock {
300 fn now(&self) -> Instant {
301 let n = self.counter.fetch_add(1, Ordering::SeqCst);
302 Instant {
303 physical_ms: 0,
304 logical: (n & 0xFFFF) as u16,
305 }
306 }
307}
308
309pub struct HlcClock {
317 wall: WallClock,
318 last: std::sync::Mutex<Instant>,
319}
320
321crate::define_named!(HlcClock, "hlc");
322
323impl Default for HlcClock {
324 fn default() -> Self {
325 Self::new()
326 }
327}
328
329impl HlcClock {
330 #[must_use]
332 pub fn new() -> Self {
333 let wall = WallClock;
334 let initial = wall.now();
335 Self {
336 wall,
337 last: std::sync::Mutex::new(initial),
338 }
339 }
340}
341
342impl Clock for HlcClock {
343 fn now(&self) -> Instant {
344 let wall_now = self.wall.now();
345 let mut last = self.last.lock().unwrap();
346 *last = Instant::tick(wall_now, *last);
347 *last
348 }
349
350 fn tick(&self, observed: Instant) -> Instant {
351 let wall_now = self.wall.now();
352 let mut last = self.last.lock().unwrap();
353 let candidate = wall_now.max(observed).max(*last);
355 *last = if candidate == *last || candidate == observed || candidate == wall_now {
356 Instant {
357 physical_ms: candidate.physical_ms,
358 logical: candidate.logical.saturating_add(1),
359 }
360 } else {
361 candidate
362 };
363 *last
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[test]
374 fn instant_total_order_lexicographic() {
375 let a = Instant::new(100, 5);
376 let b = Instant::new(100, 6);
377 let c = Instant::new(101, 0);
378 assert!(b > a);
379 assert!(c > b);
380 assert!(c > a);
381 }
382
383 #[test]
384 fn instant_zero_is_minimal() {
385 assert!(Instant::new(1, 0) > Instant::zero());
386 assert!(Instant::new(0, 1) > Instant::zero());
387 }
388
389 #[test]
390 fn instant_from_ms_yields_logical_zero() {
391 let i = Instant::from_ms(42_000);
392 assert_eq!(i.physical_ms, 42_000);
393 assert_eq!(i.logical, 0);
394 assert_eq!(i, Instant::new(42_000, 0));
395 }
396
397 #[test]
398 fn instant_from_ms_zero_equals_zero() {
399 assert_eq!(Instant::from_ms(0), Instant::zero());
400 }
401
402 #[test]
403 fn instant_pack_unpack_round_trip() {
404 for i in [
405 Instant::zero(),
406 Instant::new(1, 0),
407 Instant::new(0, 1),
408 Instant::new(1000, 5),
409 Instant::new(u64::MAX >> 16, u16::MAX),
410 ] {
411 assert_eq!(Instant::from_packed(i.to_packed()), i);
412 }
413 }
414
415 #[test]
416 fn instant_to_bytes_is_eight() {
417 let i = Instant::new(100, 5);
418 assert_eq!(i.to_bytes().len(), 8);
419 }
420
421 #[test]
422 fn instant_causally_after_strict() {
423 let a = Instant::new(10, 0);
424 let b = Instant::new(10, 0);
425 assert!(!a.causally_after(&b));
426 assert!(!b.causally_after(&a));
427 }
428
429 #[test]
430 fn instant_tick_advances_wall_clock_when_strictly_after() {
431 let prev = Instant::new(100, 5);
432 let now = Instant::new(200, 0);
433 let next = Instant::tick(now, prev);
434 assert_eq!(next, now);
435 }
436
437 #[test]
438 fn instant_tick_bumps_logical_on_tie() {
439 let prev = Instant::new(100, 5);
440 let now = Instant::new(100, 5);
441 let next = Instant::tick(now, prev);
442 assert_eq!(next, Instant::new(100, 6));
443 }
444
445 #[test]
446 fn instant_tick_bumps_logical_when_wall_goes_backward() {
447 let prev = Instant::new(200, 3);
448 let now = Instant::new(100, 0); let next = Instant::tick(now, prev);
450 assert_eq!(next.physical_ms, 200);
451 assert_eq!(next.logical, 4);
452 }
453
454 #[test]
455 fn instant_display_renders_dot_separated() {
456 let i = Instant::new(1234, 42);
457 assert_eq!(format!("{i}"), "1234.00042");
458 }
459
460 #[test]
461 fn instant_serde_round_trips() {
462 let i = Instant::new(1234, 56);
463 let bytes = serde_json::to_vec(&i).unwrap();
464 let back: Instant = serde_json::from_slice(&bytes).unwrap();
465 assert_eq!(back, i);
466 }
467
468 #[test]
469 fn instant_fingerprint_deterministic() {
470 use crate::Fingerprint;
471 let i = Instant::new(1, 2);
472 assert_eq!(i.fingerprint(), i.fingerprint());
473 }
474
475 #[test]
478 fn wallclock_now_returns_nonzero_recent_time() {
479 let w = WallClock;
480 let now = w.now();
481 assert!(now.physical_ms > 1_500_000_000_000);
483 assert_eq!(now.logical, 0);
484 }
485
486 #[test]
487 fn wallclock_named() {
488 assert_eq!(WallClock.name(), "wall");
489 }
490
491 #[test]
494 fn frozen_clock_returns_fixed_instant() {
495 let c = FrozenClock::at(1000);
496 assert_eq!(c.now(), Instant::new(1000, 0));
497 assert_eq!(c.now(), c.now());
499 }
500
501 #[test]
502 fn frozen_clock_advance_mutates_physical() {
503 let c = FrozenClock::at(100);
504 c.advance(50);
505 assert_eq!(c.now(), Instant::new(150, 0));
506 }
507
508 #[test]
509 fn frozen_clock_tick_logical_bumps_counter() {
510 let c = FrozenClock::at(100);
511 c.tick_logical();
512 c.tick_logical();
513 assert_eq!(c.now(), Instant::new(100, 2));
514 }
515
516 #[test]
517 fn frozen_clock_reset_zeroes_state() {
518 let c = FrozenClock::at(100);
519 c.advance(50);
520 c.tick_logical();
521 c.reset();
522 assert_eq!(c.now(), Instant::zero());
523 }
524
525 #[test]
526 fn frozen_clock_named() {
527 assert_eq!(FrozenClock::at(0).name(), "frozen");
528 }
529
530 #[test]
533 fn logical_clock_advances_on_now() {
534 let c = LogicalClock::new();
535 let a = c.now();
536 let b = c.now();
537 assert!(b > a);
538 }
539
540 #[test]
541 fn logical_clock_peek_doesnt_advance() {
542 let c = LogicalClock::new();
543 let _ = c.now(); let p1 = c.peek();
545 let p2 = c.peek();
546 assert_eq!(p1, p2);
547 }
548
549 #[test]
550 fn logical_clock_named() {
551 assert_eq!(LogicalClock::new().name(), "logical");
552 }
553
554 #[test]
557 fn hlc_clock_now_is_monotonic() {
558 let c = HlcClock::new();
559 let a = c.now();
560 let b = c.now();
561 assert!(b > a);
563 }
564
565 #[test]
566 fn hlc_clock_tick_merges_with_observed() {
567 let c = HlcClock::new();
568 let observed = Instant::new(u64::MAX >> 16, 0); let merged = c.tick(observed);
570 assert!(merged > observed);
572 }
573
574 #[test]
575 fn hlc_clock_named() {
576 assert_eq!(HlcClock::new().name(), "hlc");
577 }
578
579 #[test]
582 fn clock_trait_object_dispatch() {
583 let clocks: Vec<Box<dyn Clock>> = vec![
584 Box::new(WallClock),
585 Box::new(FrozenClock::at(100)),
586 Box::new(LogicalClock::new()),
587 Box::new(HlcClock::new()),
588 ];
589 for c in &clocks {
590 let _ = c.now();
591 let _ = c.name();
592 }
593 }
594}