Skip to main content

atomr_core/util/
clock.rs

1//! Monotonic / system clock abstractions.
2
3use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
4
5/// Monotonic, non-decreasing clock.
6#[derive(Debug, Clone, Copy, Default)]
7pub struct MonotonicClock;
8
9impl MonotonicClock {
10    pub fn now(&self) -> Instant {
11        Instant::now()
12    }
13
14    pub fn elapsed(&self, since: Instant) -> Duration {
15        self.now().duration_since(since)
16    }
17}
18
19/// Wall-clock.
20#[derive(Debug, Clone, Copy, Default)]
21pub struct SystemClock;
22
23impl SystemClock {
24    pub fn now(&self) -> SystemTime {
25        SystemTime::now()
26    }
27
28    pub fn millis_since_epoch(&self) -> u64 {
29        self.now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn monotonic_non_decreasing() {
39        let c = MonotonicClock;
40        let a = c.now();
41        let b = c.now();
42        assert!(b >= a);
43    }
44
45    #[test]
46    fn system_clock_returns_epoch_millis() {
47        let c = SystemClock;
48        assert!(c.millis_since_epoch() > 0);
49    }
50}