1use std::sync::Mutex;
12use std::time::Duration;
13
14pub trait Clock: Send + Sync + 'static {
24 fn now(&self) -> f64;
26
27 fn elapsed_since(&self, earlier: f64) -> f64 {
29 (self.now() - earlier).max(0.0)
30 }
31}
32
33#[derive(Debug, Default)]
35pub struct ManualClock {
41 seconds: Mutex<f64>,
42}
43
44impl ManualClock {
45 pub fn new() -> Self {
47 Self::default()
48 }
49
50 pub fn at(seconds: f64) -> Self {
52 Self {
53 seconds: Mutex::new(seconds),
54 }
55 }
56
57 pub fn set(&self, seconds: f64) {
59 if let Ok(mut current) = self.seconds.lock() {
60 *current = seconds;
61 }
62 }
63
64 pub fn advance(&self, seconds: f64) {
66 if let Ok(mut current) = self.seconds.lock() {
67 *current += seconds;
68 }
69 }
70}
71
72impl Clock for ManualClock {
73 fn now(&self) -> f64 {
74 self.seconds.lock().map(|seconds| *seconds).unwrap_or(0.0)
75 }
76}
77
78#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
80#[derive(Debug)]
81pub struct SystemClock {
87 origin: std::time::Instant,
88}
89
90#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
91impl Default for SystemClock {
92 fn default() -> Self {
93 Self::new()
94 }
95}
96
97#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
98impl SystemClock {
99 pub fn new() -> Self {
101 Self {
102 origin: std::time::Instant::now(),
103 }
104 }
105}
106
107#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
108impl Clock for SystemClock {
109 fn now(&self) -> f64 {
110 self.origin.elapsed().as_secs_f64()
111 }
112}
113
114#[cfg(target_arch = "wasm32")]
120#[derive(Debug, Default)]
121pub struct PerformanceClock {
122 seconds: std::sync::Mutex<f64>,
123}
124
125#[cfg(target_arch = "wasm32")]
126impl PerformanceClock {
127 pub fn new() -> Self {
129 Self::default()
130 }
131
132 pub fn tick(&self, delta: f64) {
134 if let Ok(mut seconds) = self.seconds.lock() {
135 *seconds += delta.max(0.0);
136 }
137 }
138
139 pub fn set(&self, seconds: f64) {
141 if let Ok(mut current) = self.seconds.lock() {
142 *current = seconds.max(0.0);
143 }
144 }
145}
146
147#[cfg(target_arch = "wasm32")]
148impl Clock for PerformanceClock {
149 fn now(&self) -> f64 {
150 self.seconds.lock().map(|seconds| *seconds).unwrap_or(0.0)
151 }
152}
153
154pub fn seconds(duration: Duration) -> f64 {
161 duration.as_secs_f64()
162}
163
164#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn a_manual_clock_moves_without_sleeping() {
171 let clock = ManualClock::new();
172 assert_eq!(clock.now(), 0.0);
173 clock.advance(1.5);
174 assert_eq!(clock.now(), 1.5);
175 assert_eq!(clock.elapsed_since(0.5), 1.0);
176 clock.set(10.0);
177 assert_eq!(clock.now(), 10.0);
178 assert_eq!(clock.elapsed_since(12.0), 0.0);
179 }
180
181 #[test]
182 fn the_system_clock_is_monotonic() {
183 #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
184 {
185 let clock = SystemClock::new();
186 let first = clock.now();
187 let second = clock.now();
188 assert!(second >= first);
189 }
190 }
191}