1use std::fmt;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::time::{Duration, Instant};
14
15pub trait Clock: fmt::Debug + Send + Sync {
17 fn now(&self) -> Duration;
19}
20
21#[derive(Debug, Clone, Copy)]
26pub struct SystemClock {
27 origin: Instant,
28}
29
30impl SystemClock {
31 pub fn new() -> Self {
33 Self {
34 origin: Instant::now(),
35 }
36 }
37}
38
39impl Default for SystemClock {
40 fn default() -> Self {
41 Self::new()
42 }
43}
44
45impl Clock for SystemClock {
46 fn now(&self) -> Duration {
47 self.origin.elapsed()
48 }
49}
50
51#[derive(Debug, Default)]
58pub struct ManualClock {
59 nanos: AtomicU64,
60}
61
62impl ManualClock {
63 pub fn new() -> Self {
65 Self::default()
66 }
67
68 pub fn advance(&self, by: Duration) {
70 let by = u64::try_from(by.as_nanos()).unwrap_or(u64::MAX);
71 let mut current = self.nanos.load(Ordering::SeqCst);
72 loop {
73 let next = current.saturating_add(by);
74 match self.nanos.compare_exchange_weak(
75 current,
76 next,
77 Ordering::SeqCst,
78 Ordering::SeqCst,
79 ) {
80 Ok(_) => return,
81 Err(actual) => current = actual,
82 }
83 }
84 }
85
86 pub fn set(&self, to: Duration) {
89 let to = u64::try_from(to.as_nanos()).unwrap_or(u64::MAX);
90 self.nanos.fetch_max(to, Ordering::SeqCst);
91 }
92}
93
94impl Clock for ManualClock {
95 fn now(&self) -> Duration {
96 Duration::from_nanos(self.nanos.load(Ordering::SeqCst))
97 }
98}
99
100pub(crate) fn default_clock() -> std::sync::Arc<dyn Clock> {
104 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
105 {
106 std::sync::Arc::new(ManualClock::new())
107 }
108 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
109 {
110 std::sync::Arc::new(SystemClock::new())
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 fn a_manual_clock_moves_only_forward() {
120 let clock = ManualClock::new();
121 assert_eq!(clock.now(), Duration::ZERO);
122 clock.advance(Duration::from_millis(500));
123 assert_eq!(clock.now(), Duration::from_millis(500));
124 clock.set(Duration::from_millis(200));
125 assert_eq!(clock.now(), Duration::from_millis(500), "never backwards");
126 clock.set(Duration::from_secs(2));
127 assert_eq!(clock.now(), Duration::from_secs(2));
128 }
129}