1#[cfg(not(target_arch = "wasm32"))]
16pub use std::time::Instant;
17use std::{
18 cell::RefCell,
19 sync::{Arc, Mutex},
20 time::{Duration, SystemTime},
21};
22
23#[cfg(target_arch = "wasm32")]
24pub use self::wasm::Instant;
25
26pub fn now() -> Instant {
29 CURRENT.with(|current| match &*current.borrow() {
30 Some(clock) => clock.now(),
31 None => Instant::now(),
32 })
33}
34
35pub fn unix_ms() -> f64 {
38 CURRENT.with(|current| match &*current.borrow() {
39 Some(clock) => clock.unix_ms(),
40 None => system_unix_ms(),
41 })
42}
43
44pub fn manual() -> bool {
47 CURRENT.with(|current| current.borrow().as_ref().is_some_and(Clock::is_manual))
48}
49
50pub const FRAME: Duration = Duration::from_nanos(16_666_667);
53
54thread_local! {
55 static CURRENT: RefCell<Option<Clock>> = const { RefCell::new(None) };
57}
58
59#[derive(Clone, Default)]
62pub struct Clock(Option<Arc<Mutex<Manual>>>);
63
64struct Manual {
66 origin: Instant,
69 elapsed: Duration,
71 unix_origin: f64,
73 alarms: Vec<(Instant, Box<dyn FnOnce() + Send>)>,
75 frames: bool,
77}
78
79impl std::fmt::Debug for Clock {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 f.write_str(if self.is_manual() {
82 "Clock::Manual"
83 } else {
84 "Clock::System"
85 })
86 }
87}
88
89impl Clock {
90 pub fn system() -> Clock {
92 Clock(None)
93 }
94
95 pub fn manual(start: SystemTime) -> Clock {
98 Clock(Some(Arc::new(Mutex::new(Manual {
99 origin: Instant::now(),
100 elapsed: Duration::ZERO,
101 unix_origin: epoch_ms(start),
102 alarms: Vec::new(),
103 frames: false,
104 }))))
105 }
106
107 pub fn with_frames(self) -> Clock {
113 if let Some(mut m) = self.manual_state() {
114 m.frames = true;
115 }
116 self
117 }
118
119 pub fn moves_with_frames(&self) -> bool {
122 self.manual_state().is_some_and(|m| m.frames)
123 }
124
125 pub fn is_manual(&self) -> bool {
127 self.0.is_some()
128 }
129
130 fn manual_state(&self) -> Option<std::sync::MutexGuard<'_, Manual>> {
131 self.0
132 .as_ref()
133 .map(|m| m.lock().unwrap_or_else(|e| e.into_inner()))
134 }
135
136 pub fn now(&self) -> Instant {
138 match self.manual_state() {
139 Some(m) => m.origin + m.elapsed,
140 None => Instant::now(),
141 }
142 }
143
144 pub fn unix_ms(&self) -> f64 {
146 match self.manual_state() {
147 Some(m) => m.unix_origin + m.elapsed.as_secs_f64() * 1000.0,
148 None => system_unix_ms(),
149 }
150 }
151
152 pub fn set_system_time(&self, at: SystemTime) {
155 if let Some(mut m) = self.manual_state() {
156 m.unix_origin = epoch_ms(at) - m.elapsed.as_secs_f64() * 1000.0;
157 }
158 }
159
160 pub fn advance_to(&self, at: Instant) {
163 let due = {
164 let Some(mut m) = self.manual_state() else {
165 return;
166 };
167 let elapsed = at.saturating_duration_since(m.origin);
168 m.elapsed = m.elapsed.max(elapsed);
169 let now = m.origin + m.elapsed;
170 let split = m.alarms.partition_point(|(when, _)| *when <= now);
171 m.alarms.drain(..split).collect::<Vec<_>>()
172 };
173 for (_, alarm) in due {
174 alarm();
175 }
176 }
177
178 pub fn at(&self, at: Instant, alarm: impl FnOnce() + Send + 'static) {
182 match self.manual_state() {
183 Some(mut m) => {
184 let index = m.alarms.partition_point(|(when, _)| *when <= at);
185 m.alarms.insert(index, (at, Box::new(alarm)));
186 }
187 None => {
188 #[cfg(not(target_arch = "wasm32"))]
189 std::thread::spawn(move || {
190 std::thread::sleep(at.saturating_duration_since(Instant::now()));
191 alarm();
192 });
193 #[cfg(target_arch = "wasm32")]
195 alarm();
196 }
197 }
198 }
199
200 pub fn next_alarm(&self) -> Option<Instant> {
202 self.manual_state()?.alarms.first().map(|(at, _)| *at)
203 }
204
205 pub fn enter(&self) -> ClockGuard {
208 let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
209 ClockGuard { previous }
210 }
211}
212
213#[must_use = "the clock is the thread's while the guard lives"]
215pub struct ClockGuard {
216 previous: Option<Clock>,
217}
218
219impl Drop for ClockGuard {
220 fn drop(&mut self) {
221 let previous = self.previous.take();
222 CURRENT.with(|current| *current.borrow_mut() = previous);
223 }
224}
225
226fn epoch_ms(at: SystemTime) -> f64 {
228 match at.duration_since(SystemTime::UNIX_EPOCH) {
229 Ok(since) => since.as_secs_f64() * 1000.0,
230 Err(before) => -before.duration().as_secs_f64() * 1000.0,
231 }
232}
233
234#[cfg(not(target_arch = "wasm32"))]
236fn system_unix_ms() -> f64 {
237 std::time::SystemTime::now()
238 .duration_since(std::time::UNIX_EPOCH)
239 .map_or(0.0, |d| d.as_millis() as f64)
240}
241
242#[cfg(target_arch = "wasm32")]
244fn system_unix_ms() -> f64 {
245 #[link(wasm_import_module = "nsh")]
246 unsafe extern "C" {
247 fn date_now_ms() -> f64;
248 }
249 unsafe { date_now_ms() }
251}
252
253#[cfg(target_arch = "wasm32")]
254mod wasm {
255 use std::{
256 ops::{Add, AddAssign, Sub, SubAssign},
257 time::Duration,
258 };
259
260 #[link(wasm_import_module = "nsh")]
261 unsafe extern "C" {
262 fn now_ms() -> f64;
264 }
265
266 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
268 pub struct Instant(Duration);
269
270 impl Instant {
271 pub fn now() -> Instant {
273 let ms = unsafe { now_ms() };
275 Instant(Duration::from_secs_f64(ms.max(0.0) / 1000.0))
276 }
277
278 pub fn duration_since(&self, earlier: Instant) -> Duration {
280 self.0.saturating_sub(earlier.0)
281 }
282
283 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
285 self.duration_since(earlier)
286 }
287
288 pub fn elapsed(&self) -> Duration {
290 Instant::now().duration_since(*self)
291 }
292
293 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
295 self.0.checked_add(duration).map(Instant)
296 }
297
298 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
300 self.0.checked_sub(duration).map(Instant)
301 }
302 }
303
304 impl Add<Duration> for Instant {
305 type Output = Instant;
306 fn add(self, rhs: Duration) -> Instant {
307 Instant(self.0 + rhs)
308 }
309 }
310
311 impl AddAssign<Duration> for Instant {
312 fn add_assign(&mut self, rhs: Duration) {
313 self.0 += rhs;
314 }
315 }
316
317 impl Sub<Duration> for Instant {
318 type Output = Instant;
319 fn sub(self, rhs: Duration) -> Instant {
320 Instant(self.0.saturating_sub(rhs))
321 }
322 }
323
324 impl SubAssign<Duration> for Instant {
325 fn sub_assign(&mut self, rhs: Duration) {
326 self.0 = self.0.saturating_sub(rhs);
327 }
328 }
329
330 impl Sub<Instant> for Instant {
331 type Output = Duration;
332 fn sub(self, rhs: Instant) -> Duration {
333 self.duration_since(rhs)
334 }
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 #[test]
343 fn a_manual_clock_moves_only_when_told_and_runs_its_alarms_in_order() {
344 let clock = Clock::manual(SystemTime::UNIX_EPOCH + Duration::from_secs(1));
345 let start = clock.now();
346 std::thread::sleep(Duration::from_millis(5));
347 assert_eq!(clock.now(), start);
348 let rang = Arc::new(Mutex::new(Vec::new()));
349 for (ms, name) in [(30, "b"), (10, "a"), (50, "c")] {
350 let rang = rang.clone();
351 clock.at(start + Duration::from_millis(ms), move || {
352 rang.lock().unwrap().push(name)
353 });
354 }
355 assert_eq!(clock.next_alarm(), Some(start + Duration::from_millis(10)));
356 clock.advance_to(start + Duration::from_millis(30));
357 assert_eq!(*rang.lock().unwrap(), ["a", "b"]);
358 assert_eq!(clock.unix_ms(), 1_030.0);
359 clock.advance_to(start);
361 assert_eq!(clock.now(), start + Duration::from_millis(30));
362 clock.set_system_time(SystemTime::UNIX_EPOCH + Duration::from_secs(5));
363 assert_eq!(
364 (clock.unix_ms(), clock.now()),
365 (5_000.0, start + Duration::from_millis(30))
366 );
367 }
368
369 #[test]
370 fn a_thread_reads_its_engine_s_clock_while_it_is_entered() {
371 assert!(!manual());
372 let clock = Clock::manual(SystemTime::UNIX_EPOCH + Duration::from_millis(42));
373 {
374 let _guard = clock.enter();
375 assert!(manual());
376 assert_eq!((now(), unix_ms()), (clock.now(), 42.0));
377 }
378 assert!(!manual());
379 assert!(unix_ms() > 1.0e12);
380 }
381}