Skip to main content

icedwright_probe/
time.rs

1//! The clock components should read instead of `Instant::now()`, so a harness can move it.
2//!
3//! Without the `control` feature these are the real clock. With it, a harness installs its
4//! virtual clock once per process, and each call answers for the thread that makes it.
5
6use std::time::{Instant, SystemTime};
7
8/// The current instant: the harness's virtual instant under a harness, the real one otherwise.
9#[must_use]
10#[inline]
11#[expect(
12    clippy::disallowed_methods,
13    reason = "the probe clock is the real clock unless a harness installs its virtual one"
14)]
15pub fn now() -> Instant {
16    #[cfg(feature = "control")]
17    if let Some(hooks) = hooks::get() {
18        return (hooks.now)();
19    }
20    Instant::now()
21}
22
23/// The current wall-clock time: the harness's virtual wall clock under a harness, the real
24/// one otherwise.
25#[must_use]
26#[inline]
27#[expect(
28    clippy::disallowed_methods,
29    reason = "the probe clock is the real clock unless a harness installs its virtual one"
30)]
31pub fn system_now() -> SystemTime {
32    #[cfg(feature = "control")]
33    if let Some(hooks) = hooks::get() {
34        return (hooks.system_now)();
35    }
36    SystemTime::now()
37}
38
39/// Declares that `component` runs a timer on the real clock, such as a ticker thread. A
40/// harness refuses the step that creates it, because its ticks would depend on real time.
41/// Outside a harness it does nothing.
42#[inline]
43pub fn real_timer(component: &'static str) {
44    #[cfg(feature = "control")]
45    if let Some(controller) = crate::control::current() {
46        controller.real_timer(component);
47    }
48    #[cfg(not(feature = "control"))]
49    let _ = component;
50}
51
52#[cfg(feature = "control")]
53pub use hooks::install;
54
55#[cfg(feature = "control")]
56mod hooks {
57    use std::sync::{PoisonError, RwLock};
58    use std::time::{Instant, SystemTime};
59
60    #[derive(Clone, Copy)]
61    pub(super) struct Hooks {
62        pub(super) now: fn() -> Instant,
63        pub(super) system_now: fn() -> SystemTime,
64    }
65
66    static HOOKS: RwLock<Option<Hooks>> = RwLock::new(None);
67
68    /// Makes [`now`](super::now) and [`system_now`](super::system_now) call these for the
69    /// rest of the process. A harness installs functions that read the calling thread's
70    /// virtual clock, so one install serves every test thread. Installing again replaces them.
71    #[doc(hidden)]
72    pub fn install(now: fn() -> Instant, system_now: fn() -> SystemTime) {
73        *HOOKS.write().unwrap_or_else(PoisonError::into_inner) = Some(Hooks { now, system_now });
74    }
75
76    pub(super) fn get() -> Option<Hooks> {
77        *HOOKS.read().unwrap_or_else(PoisonError::into_inner)
78    }
79}