Skip to main content

serenade_scheduler/
clock.rs

1//! Injectable clocks for the scheduler runner.
2
3use std::sync::Mutex;
4use std::time::{Duration, SystemTime};
5
6/// Source of “now” for [`crate::Scheduler::tick`].
7pub trait Clock: Send + Sync {
8    /// Current instant used for due checks.
9    fn now(&self) -> SystemTime;
10}
11
12/// Wall-clock [`Clock`].
13#[derive(Clone, Copy, Debug, Default)]
14pub struct SystemClock;
15
16impl Clock for SystemClock {
17    fn now(&self) -> SystemTime {
18        SystemTime::now()
19    }
20}
21
22/// Test [`Clock`] with an explicit current time.
23#[derive(Debug)]
24pub struct ManualClock {
25    now: Mutex<SystemTime>,
26}
27
28impl ManualClock {
29    /// Starts at `now`.
30    #[must_use]
31    pub const fn new(now: SystemTime) -> Self {
32        Self {
33            now: Mutex::new(now),
34        }
35    }
36
37    /// Advances the clock by `delta`.
38    ///
39    /// # Panics
40    ///
41    /// Panics when the internal mutex is poisoned.
42    pub fn advance(&self, delta: Duration) {
43        let mut guard = self
44            .now
45            .lock()
46            .expect("serenade-scheduler ManualClock mutex poisoned");
47        *guard += delta;
48    }
49
50    /// Sets the clock to an absolute instant.
51    ///
52    /// # Panics
53    ///
54    /// Panics when the internal mutex is poisoned.
55    pub fn set(&self, now: SystemTime) {
56        let mut guard = self
57            .now
58            .lock()
59            .expect("serenade-scheduler ManualClock mutex poisoned");
60        *guard = now;
61    }
62}
63
64impl Clock for ManualClock {
65    fn now(&self) -> SystemTime {
66        *self
67            .now
68            .lock()
69            .expect("serenade-scheduler ManualClock mutex poisoned")
70    }
71}