Skip to main content

egui_pop_model/
clock.rs

1//! Clocks: where "now" comes from, injected so tests can fix it.
2//!
3//! The jobs model (time left, how long a job ran) and the motion clock
4//! (spinners, delays, shimmer) read a [`Clock`] instead of the system's
5//! time: an application gives none and gets the interface's own time; a
6//! test gives a [`ManualClock`] and moves it by hand.
7//!
8//! ```
9//! use egui_pop_model::clock::{Clock, ManualClock};
10//!
11//! let clock = ManualClock::new(10.0);
12//! clock.advance(0.25);
13//! assert_eq!(clock.now(), 10.25);
14//! ```
15
16use std::fmt;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20/// A source of time, in seconds from an origin of its own.
21pub trait Clock: Send + Sync {
22    /// Now, in seconds.
23    fn now(&self) -> f64;
24}
25
26/// A clock shared between its users.
27pub type SharedClock = Arc<dyn Clock>;
28
29/// A clock that moves only when told: tests freeze, set and step it.
30/// Clones share the same time.
31#[derive(Clone, Default)]
32pub struct ManualClock(Arc<AtomicU64>);
33
34impl fmt::Debug for ManualClock {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "ManualClock({})", self.now())
37    }
38}
39
40impl ManualClock {
41    /// A clock showing `now` seconds.
42    pub fn new(now: f64) -> Self {
43        let c = Self::default();
44        c.set(now);
45        c
46    }
47
48    /// Sets the time.
49    pub fn set(&self, now: f64) {
50        self.0.store(now.to_bits(), Ordering::Relaxed);
51    }
52
53    /// Moves the time on by `seconds`.
54    pub fn advance(&self, seconds: f64) {
55        self.set(self.now() + seconds);
56    }
57
58    /// Shared, as the jobs model and the motion clock take it.
59    pub fn shared(&self) -> SharedClock {
60        Arc::new(self.clone())
61    }
62}
63
64impl Clock for ManualClock {
65    fn now(&self) -> f64 {
66        f64::from_bits(self.0.load(Ordering::Relaxed))
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn clones_share_the_time() {
76        let a = ManualClock::new(1.0);
77        let b = a.clone();
78        b.advance(2.5);
79        assert_eq!(a.now(), 3.5);
80        assert_eq!(a.shared().now(), 3.5);
81    }
82}