Skip to main content

nsh_core/
time.rs

1//! A monotonic clock that also works in WebAssembly, and the clocks of
2//! engines.
3//!
4//! `std::time::Instant::now` panics on `wasm32-unknown-unknown`, which has
5//! no clock of its own. Off WebAssembly [`Instant`] is the standard one; in
6//! WebAssembly it counts from the page's time origin (`performance.now()`,
7//! the `nsh.now_ms` import the web runtime provides).
8//!
9//! An engine runs on a [`Clock`]: the system's, or a manual one that moves
10//! only when told ([`Clock::advance_to`]), for tests that skip through
11//! timers and animations. The engine makes its clock its thread's
12//! ([`Clock::enter`]), so [`now`] and [`unix_ms`], which timers, tasks and
13//! `Date` read, are its time there.
14
15#[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
26/// Now on the current thread's clock: its engine's ([`Clock::enter`]),
27/// else the system's.
28pub fn now() -> Instant {
29    CURRENT.with(|current| match &*current.borrow() {
30        Some(clock) => clock.now(),
31        None => Instant::now(),
32    })
33}
34
35/// Milliseconds since the Unix epoch on the current thread's clock (wall
36/// clock: `Date.now()`).
37pub 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
44/// Whether the current thread's clock is manual: time moves only when it
45/// is told to.
46pub fn manual() -> bool {
47    CURRENT.with(|current| current.borrow().as_ref().is_some_and(Clock::is_manual))
48}
49
50/// A display frame's time at 60 Hz: what a manual clock that moves with
51/// the display's frames moves by each frame ([`Clock::with_frames`]).
52pub const FRAME: Duration = Duration::from_nanos(16_666_667);
53
54thread_local! {
55    /// The clock of the engine on this thread.
56    static CURRENT: RefCell<Option<Clock>> = const { RefCell::new(None) };
57}
58
59/// The time an engine runs on: the system's, or a manual clock that moves
60/// only when told, shared by the threads that drive the engine (a test's).
61#[derive(Clone, Default)]
62pub struct Clock(Option<Arc<Mutex<Manual>>>);
63
64/// A manual clock's state.
65struct Manual {
66    /// The system's time when it started: its instants are this plus
67    /// `elapsed`.
68    origin: Instant,
69    /// How far it moved.
70    elapsed: Duration,
71    /// The wall clock at `origin`, in milliseconds since the Unix epoch.
72    unix_origin: f64,
73    /// What runs once it reaches a time ([`Clock::at`]), soonest first.
74    alarms: Vec<(Instant, Box<dyn FnOnce() + Send>)>,
75    /// It also moves with the display's frames ([`Clock::with_frames`]).
76    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    /// The system's clock.
91    pub fn system() -> Clock {
92        Clock(None)
93    }
94
95    /// A manual clock standing at the wall time `start`, which moves only
96    /// when told.
97    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    /// A manual clock that also moves by a frame's time
108    /// ([`FRAME`]) with each frame the display shows its engine, before
109    /// the frame runs: a test's app on a real platform, whose time passes
110    /// while it animates and stands still while it is idle, as a headless
111    /// run's does. Nothing for the system's clock.
112    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    /// Whether it is a manual clock that moves with the display's frames
120    /// ([`Clock::with_frames`]).
121    pub fn moves_with_frames(&self) -> bool {
122        self.manual_state().is_some_and(|m| m.frames)
123    }
124
125    /// Whether it is manual.
126    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    /// Now.
137    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    /// Milliseconds since the Unix epoch.
145    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    /// Sets a manual clock's wall time (`Date.now()`) to `at`, without
153    /// moving its instants: no timer comes due. Nothing on the system's.
154    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    /// Moves a manual clock forward to `at` (never back), and runs the
161    /// alarms due by then, in order. Nothing on the system's.
162    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    /// Runs `alarm` once the clock reaches `at`: on a thread of its own
179    /// for the system's clock, when it is moved past `at` for a manual
180    /// one.
181    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                // No threads to sleep on: at once.
194                #[cfg(target_arch = "wasm32")]
195                alarm();
196            }
197        }
198    }
199
200    /// When a manual clock's next alarm is due.
201    pub fn next_alarm(&self) -> Option<Instant> {
202        self.manual_state()?.alarms.first().map(|(at, _)| *at)
203    }
204
205    /// Makes it the current thread's clock until the guard drops: what
206    /// [`now`], [`unix_ms`] and [`manual`] read.
207    pub fn enter(&self) -> ClockGuard {
208        let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
209        ClockGuard { previous }
210    }
211}
212
213/// Puts the thread's previous clock back ([`Clock::enter`]).
214#[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
226/// `at` in milliseconds since the Unix epoch (negative before it).
227fn 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/// Milliseconds since the Unix epoch (the system's wall clock).
235#[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/// Milliseconds since the Unix epoch (the system's wall clock).
243#[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    // SAFETY: a pure host function without arguments.
250    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        /// Milliseconds since the page's time origin (`performance.now()`).
263        fn now_ms() -> f64;
264    }
265
266    /// A point in time, from the page's time origin.
267    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
268    pub struct Instant(Duration);
269
270    impl Instant {
271        /// Now.
272        pub fn now() -> Instant {
273            // SAFETY: a pure host function without arguments.
274            let ms = unsafe { now_ms() };
275            Instant(Duration::from_secs_f64(ms.max(0.0) / 1000.0))
276        }
277
278        /// The time from `earlier` to `self` (zero if `earlier` is later).
279        pub fn duration_since(&self, earlier: Instant) -> Duration {
280            self.0.saturating_sub(earlier.0)
281        }
282
283        /// As [`Instant::duration_since`].
284        pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
285            self.duration_since(earlier)
286        }
287
288        /// The time since `self`.
289        pub fn elapsed(&self) -> Duration {
290            Instant::now().duration_since(*self)
291        }
292
293        /// `self + duration`, if representable.
294        pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
295            self.0.checked_add(duration).map(Instant)
296        }
297
298        /// `self - duration`, if representable.
299        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        // Never back.
360        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}