Skip to main content

crisol_core/
time.rs

1//! Injectable time. The core never reads a wall clock on its own.
2//!
3//! History, jobs, debounce, and key sequences take a [`Clock`]. Native builds use
4//! [`SystemClock`], wasm builds use `PerformanceClock`, and tests use [`ManualClock`]
5//! and never sleep (CORE-DET-02).
6//!
7//! ```
8//! use crisol_core::time;
9//! ```
10
11use std::sync::Mutex;
12use std::time::Duration;
13
14/// A monotonic source of seconds.
15///
16/// The origin is arbitrary; only differences are meaningful. Implementations must be
17/// cheap and thread-safe.
18/// # Example
19///
20/// ```
21/// use crisol_core::time::Clock;
22/// ```
23pub trait Clock: Send + Sync + 'static {
24    /// Seconds since this clock's origin.
25    fn now(&self) -> f64;
26
27    /// A duration since an earlier `now()` value, never negative.
28    fn elapsed_since(&self, earlier: f64) -> f64 {
29        (self.now() - earlier).max(0.0)
30    }
31}
32
33/// A clock for tests and deterministic replays.
34#[derive(Debug, Default)]
35/// # Example
36///
37/// ```
38/// use crisol_core::time::ManualClock;
39/// ```
40pub struct ManualClock {
41    seconds: Mutex<f64>,
42}
43
44impl ManualClock {
45    /// A clock at zero.
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// A clock at `seconds`.
51    pub fn at(seconds: f64) -> Self {
52        Self {
53            seconds: Mutex::new(seconds),
54        }
55    }
56
57    /// Move the clock to `seconds`.
58    pub fn set(&self, seconds: f64) {
59        if let Ok(mut current) = self.seconds.lock() {
60            *current = seconds;
61        }
62    }
63
64    /// Move the clock forward.
65    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/// A native monotonic clock backed by `Instant`.
79#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
80#[derive(Debug)]
81/// # Example
82///
83/// ```
84/// use crisol_core::time::SystemClock;
85/// ```
86pub 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    /// A clock whose origin is now.
100    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/// A wasm clock that counts cooperative steps between frames.
115///
116/// The host calls [`PerformanceClock::tick`] once per frame with the frame delta; the
117/// core then has time without touching `std::time` (which is unavailable on
118/// `wasm32-unknown-unknown`).
119#[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    /// A clock at zero.
128    pub fn new() -> Self {
129        Self::default()
130    }
131
132    /// Add one frame delta in seconds.
133    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    /// Set the elapsed time directly.
140    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
154/// Convert a `Duration` to seconds.
155/// # Example
156///
157/// ```
158/// use crisol_core::time::seconds;
159/// ```
160pub fn seconds(duration: Duration) -> f64 {
161    duration.as_secs_f64()
162}
163
164// spec: CORE-DET-02
165#[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}