Skip to main content

sew_proto/
clock.rs

1//! The one time source.
2//!
3//! Product code reads time only through a [`Clock`], so tests can move time. This module holds
4//! the only `SystemTime::now` call in the crate.
5
6use std::sync::Arc;
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use crate::time::Timestamp;
10
11/// A source of wall-clock time that tests can replace.
12pub trait Clock: Send + Sync {
13    /// Milliseconds since the Unix epoch.
14    fn now_unix_ms(&self) -> u64;
15
16    /// Waits `ms` milliseconds. `0` means "yield once".
17    fn sleep_ms(&self, ms: u64);
18
19    /// The current time as a [`Timestamp`].
20    fn now(&self) -> Timestamp {
21        Timestamp::from_unix_ms_saturating(self.now_unix_ms())
22    }
23}
24
25/// The real clock: `SystemTime::now` and `std::thread::sleep`.
26#[derive(Debug, Clone, Copy, Default)]
27pub struct SystemClock;
28
29impl Clock for SystemClock {
30    fn now_unix_ms(&self) -> u64 {
31        match SystemTime::now().duration_since(UNIX_EPOCH) {
32            Ok(d) => u64::try_from(d.as_millis()).unwrap_or(u64::MAX),
33            // A clock before 1970 reads as 0; the id generator then refuses it loudly.
34            Err(_) => 0,
35        }
36    }
37
38    fn sleep_ms(&self, ms: u64) {
39        if ms == 0 {
40            std::thread::yield_now();
41        } else {
42            std::thread::sleep(std::time::Duration::from_millis(ms));
43        }
44    }
45}
46
47impl<C: Clock + ?Sized> Clock for Arc<C> {
48    fn now_unix_ms(&self) -> u64 {
49        (**self).now_unix_ms()
50    }
51    fn sleep_ms(&self, ms: u64) {
52        (**self).sleep_ms(ms)
53    }
54}
55
56impl<C: Clock + ?Sized> Clock for Box<C> {
57    fn now_unix_ms(&self) -> u64 {
58        (**self).now_unix_ms()
59    }
60    fn sleep_ms(&self, ms: u64) {
61        (**self).sleep_ms(ms)
62    }
63}
64
65impl<C: Clock + ?Sized> Clock for &C {
66    fn now_unix_ms(&self) -> u64 {
67        (**self).now_unix_ms()
68    }
69    fn sleep_ms(&self, ms: u64) {
70        (**self).sleep_ms(ms)
71    }
72}