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/// The current thread's clock ([`Clock::enter`]), else the system's: for
51/// what keeps reading an engine's time outside its calls (a browser realm's
52/// `Date` between pumps).
53pub fn current() -> Clock {
54    CURRENT.with(|current| current.borrow().clone().unwrap_or_default())
55}
56
57/// A display frame's time at 60 Hz: what a manual clock that moves with
58/// the display's frames moves by each frame ([`Clock::with_frames`]).
59pub const FRAME: Duration = Duration::from_nanos(16_666_667);
60
61thread_local! {
62    /// The clock of the engine on this thread.
63    static CURRENT: RefCell<Option<Clock>> = const { RefCell::new(None) };
64}
65
66/// The time an engine runs on: the system's, or a manual clock that moves
67/// only when told, shared by the threads that drive the engine (a test's).
68#[derive(Clone, Default)]
69pub struct Clock(Option<Arc<Mutex<Manual>>>);
70
71/// A manual clock's state.
72struct Manual {
73    /// The system's time when it started: its instants are this plus
74    /// `elapsed`.
75    origin: Instant,
76    /// How far it moved.
77    elapsed: Duration,
78    /// The wall clock at `origin`, in milliseconds since the Unix epoch.
79    unix_origin: f64,
80    /// What runs once it reaches a time ([`Clock::at`]), soonest first.
81    alarms: Vec<(Instant, Box<dyn FnOnce() + Send>)>,
82    /// It also moves with the display's frames ([`Clock::with_frames`]).
83    frames: bool,
84}
85
86impl std::fmt::Debug for Clock {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.write_str(if self.is_manual() {
89            "Clock::Manual"
90        } else {
91            "Clock::System"
92        })
93    }
94}
95
96impl Clock {
97    /// The system's clock.
98    pub fn system() -> Clock {
99        Clock(None)
100    }
101
102    /// A manual clock standing at the wall time `start`, which moves only
103    /// when told.
104    pub fn manual(start: SystemTime) -> Clock {
105        Clock(Some(Arc::new(Mutex::new(Manual {
106            origin: Instant::now(),
107            elapsed: Duration::ZERO,
108            unix_origin: epoch_ms(start),
109            alarms: Vec::new(),
110            frames: false,
111        }))))
112    }
113
114    /// A manual clock that also moves by a frame's time
115    /// ([`FRAME`]) with each frame the display shows its engine, before
116    /// the frame runs: a test's app on a real platform, whose time passes
117    /// while it animates and stands still while it is idle, as a headless
118    /// run's does. Nothing for the system's clock.
119    pub fn with_frames(self) -> Clock {
120        if let Some(mut m) = self.manual_state() {
121            m.frames = true;
122        }
123        self
124    }
125
126    /// Whether it is a manual clock that moves with the display's frames
127    /// ([`Clock::with_frames`]).
128    pub fn moves_with_frames(&self) -> bool {
129        self.manual_state().is_some_and(|m| m.frames)
130    }
131
132    /// Whether it is manual.
133    pub fn is_manual(&self) -> bool {
134        self.0.is_some()
135    }
136
137    fn manual_state(&self) -> Option<std::sync::MutexGuard<'_, Manual>> {
138        self.0
139            .as_ref()
140            .map(|m| m.lock().unwrap_or_else(|e| e.into_inner()))
141    }
142
143    /// Now.
144    pub fn now(&self) -> Instant {
145        match self.manual_state() {
146            Some(m) => m.origin + m.elapsed,
147            None => Instant::now(),
148        }
149    }
150
151    /// Milliseconds since the Unix epoch.
152    pub fn unix_ms(&self) -> f64 {
153        match self.manual_state() {
154            Some(m) => m.unix_origin + m.elapsed.as_secs_f64() * 1000.0,
155            None => system_unix_ms(),
156        }
157    }
158
159    /// Sets a manual clock's wall time (`Date.now()`) to `at`, without
160    /// moving its instants: no timer comes due. Nothing on the system's.
161    pub fn set_system_time(&self, at: SystemTime) {
162        if let Some(mut m) = self.manual_state() {
163            m.unix_origin = epoch_ms(at) - m.elapsed.as_secs_f64() * 1000.0;
164        }
165    }
166
167    /// Moves a manual clock forward to `at` (never back), and runs the
168    /// alarms due by then, in order. Nothing on the system's.
169    pub fn advance_to(&self, at: Instant) {
170        let due = {
171            let Some(mut m) = self.manual_state() else {
172                return;
173            };
174            let elapsed = at.saturating_duration_since(m.origin);
175            m.elapsed = m.elapsed.max(elapsed);
176            let now = m.origin + m.elapsed;
177            let split = m.alarms.partition_point(|(when, _)| *when <= now);
178            m.alarms.drain(..split).collect::<Vec<_>>()
179        };
180        for (_, alarm) in due {
181            alarm();
182        }
183    }
184
185    /// Runs `alarm` once the clock reaches `at`: on a thread of its own
186    /// for the system's clock, when it is moved past `at` for a manual
187    /// one.
188    pub fn at(&self, at: Instant, alarm: impl FnOnce() + Send + 'static) {
189        match self.manual_state() {
190            Some(mut m) => {
191                let index = m.alarms.partition_point(|(when, _)| *when <= at);
192                m.alarms.insert(index, (at, Box::new(alarm)));
193            }
194            None => {
195                #[cfg(not(target_arch = "wasm32"))]
196                std::thread::spawn(move || {
197                    std::thread::sleep(at.saturating_duration_since(Instant::now()));
198                    alarm();
199                });
200                // No threads to sleep on: at once.
201                #[cfg(target_arch = "wasm32")]
202                alarm();
203            }
204        }
205    }
206
207    /// When a manual clock's next alarm is due.
208    pub fn next_alarm(&self) -> Option<Instant> {
209        self.manual_state()?.alarms.first().map(|(at, _)| *at)
210    }
211
212    /// Makes it the current thread's clock until the guard drops: what
213    /// [`now`], [`unix_ms`] and [`manual`] read.
214    pub fn enter(&self) -> ClockGuard {
215        let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
216        ClockGuard { previous }
217    }
218}
219
220/// Puts the thread's previous clock back ([`Clock::enter`]).
221#[must_use = "the clock is the thread's while the guard lives"]
222pub struct ClockGuard {
223    previous: Option<Clock>,
224}
225
226impl Drop for ClockGuard {
227    fn drop(&mut self) {
228        let previous = self.previous.take();
229        CURRENT.with(|current| *current.borrow_mut() = previous);
230    }
231}
232
233/// `at` in milliseconds since the Unix epoch (negative before it).
234fn epoch_ms(at: SystemTime) -> f64 {
235    match at.duration_since(SystemTime::UNIX_EPOCH) {
236        Ok(since) => since.as_secs_f64() * 1000.0,
237        Err(before) => -before.duration().as_secs_f64() * 1000.0,
238    }
239}
240
241/// Milliseconds since the Unix epoch (the system's wall clock).
242#[cfg(not(target_arch = "wasm32"))]
243fn system_unix_ms() -> f64 {
244    std::time::SystemTime::now()
245        .duration_since(std::time::UNIX_EPOCH)
246        .map_or(0.0, |d| d.as_millis() as f64)
247}
248
249/// Milliseconds since the Unix epoch (the system's wall clock).
250#[cfg(target_arch = "wasm32")]
251fn system_unix_ms() -> f64 {
252    #[link(wasm_import_module = "nsh")]
253    unsafe extern "C" {
254        fn date_now_ms() -> f64;
255    }
256    // SAFETY: a pure host function without arguments.
257    unsafe { date_now_ms() }
258}
259
260#[cfg(target_arch = "wasm32")]
261mod wasm {
262    use std::{
263        ops::{Add, AddAssign, Sub, SubAssign},
264        time::Duration,
265    };
266
267    #[link(wasm_import_module = "nsh")]
268    unsafe extern "C" {
269        /// Milliseconds since the page's time origin (`performance.now()`).
270        fn now_ms() -> f64;
271    }
272
273    /// A point in time, from the page's time origin.
274    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
275    pub struct Instant(Duration);
276
277    impl Instant {
278        /// Now.
279        pub fn now() -> Instant {
280            // SAFETY: a pure host function without arguments.
281            let ms = unsafe { now_ms() };
282            Instant(Duration::from_secs_f64(ms.max(0.0) / 1000.0))
283        }
284
285        /// The time from `earlier` to `self` (zero if `earlier` is later).
286        pub fn duration_since(&self, earlier: Instant) -> Duration {
287            self.0.saturating_sub(earlier.0)
288        }
289
290        /// As [`Instant::duration_since`].
291        pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
292            self.duration_since(earlier)
293        }
294
295        /// The time since `self`.
296        pub fn elapsed(&self) -> Duration {
297            Instant::now().duration_since(*self)
298        }
299
300        /// `self + duration`, if representable.
301        pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
302            self.0.checked_add(duration).map(Instant)
303        }
304
305        /// `self - duration`, if representable.
306        pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
307            self.0.checked_sub(duration).map(Instant)
308        }
309    }
310
311    impl Add<Duration> for Instant {
312        type Output = Instant;
313        fn add(self, rhs: Duration) -> Instant {
314            Instant(self.0 + rhs)
315        }
316    }
317
318    impl AddAssign<Duration> for Instant {
319        fn add_assign(&mut self, rhs: Duration) {
320            self.0 += rhs;
321        }
322    }
323
324    impl Sub<Duration> for Instant {
325        type Output = Instant;
326        fn sub(self, rhs: Duration) -> Instant {
327            Instant(self.0.saturating_sub(rhs))
328        }
329    }
330
331    impl SubAssign<Duration> for Instant {
332        fn sub_assign(&mut self, rhs: Duration) {
333            self.0 = self.0.saturating_sub(rhs);
334        }
335    }
336
337    impl Sub<Instant> for Instant {
338        type Output = Duration;
339        fn sub(self, rhs: Instant) -> Duration {
340            self.duration_since(rhs)
341        }
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    #[test]
350    fn a_manual_clock_moves_only_when_told_and_runs_its_alarms_in_order() {
351        let clock = Clock::manual(SystemTime::UNIX_EPOCH + Duration::from_secs(1));
352        let start = clock.now();
353        std::thread::sleep(Duration::from_millis(5));
354        assert_eq!(clock.now(), start);
355        let rang = Arc::new(Mutex::new(Vec::new()));
356        for (ms, name) in [(30, "b"), (10, "a"), (50, "c")] {
357            let rang = rang.clone();
358            clock.at(start + Duration::from_millis(ms), move || {
359                rang.lock().unwrap().push(name)
360            });
361        }
362        assert_eq!(clock.next_alarm(), Some(start + Duration::from_millis(10)));
363        clock.advance_to(start + Duration::from_millis(30));
364        assert_eq!(*rang.lock().unwrap(), ["a", "b"]);
365        assert_eq!(clock.unix_ms(), 1_030.0);
366        // Never back.
367        clock.advance_to(start);
368        assert_eq!(clock.now(), start + Duration::from_millis(30));
369        clock.set_system_time(SystemTime::UNIX_EPOCH + Duration::from_secs(5));
370        assert_eq!(
371            (clock.unix_ms(), clock.now()),
372            (5_000.0, start + Duration::from_millis(30))
373        );
374    }
375
376    #[test]
377    fn a_thread_reads_its_engine_s_clock_while_it_is_entered() {
378        assert!(!manual());
379        let clock = Clock::manual(SystemTime::UNIX_EPOCH + Duration::from_millis(42));
380        {
381            let _guard = clock.enter();
382            assert!(manual());
383            assert_eq!((now(), unix_ms()), (clock.now(), 42.0));
384        }
385        assert!(!manual());
386        assert!(unix_ms() > 1.0e12);
387    }
388}