Skip to main content

net_io/
time.rs

1//! Clocks. Deadlines read time through a [`Clock`] so tests can move it by hand.
2
3use std::sync::Mutex;
4use std::sync::PoisonError;
5use std::time::{Duration, Instant};
6
7/// A source of monotonic time.
8///
9/// # Examples
10///
11/// ```
12/// use net_io::{Clock, MonotonicClock};
13/// let a = MonotonicClock.now();
14/// assert!(MonotonicClock.now() >= a);
15/// ```
16pub trait Clock: Send + Sync + 'static {
17    /// The current instant.
18    fn now(&self) -> Instant;
19}
20
21/// `Instant::now()`.
22///
23/// ```
24/// use net_io::Clock;
25/// let _ = net_io::MonotonicClock.now();
26/// ```
27#[derive(Clone, Copy, Debug, Default)]
28pub struct MonotonicClock;
29
30/// A year: the longest timeout net-io takes. `Instant + Duration` panics on
31/// overflow, and `Duration::MAX` is a common way to say "no limit".
32pub(crate) const LONGEST: Duration = Duration::from_secs(365 * 24 * 3600);
33
34/// `d`, held to [`LONGEST`].
35pub(crate) fn bounded(d: Duration) -> Duration {
36    d.min(LONGEST)
37}
38
39/// The raw monotonic clock in microseconds: `CLOCK_MONOTONIC` on Linux and
40/// macOS, the performance counter on Windows. This is the value systemd's
41/// `MONOTONIC_USEC` expects (`sd_notify` reload and watchdog messages); it is
42/// not related to [`Instant`] values or to [`Clock`].
43///
44/// ```
45/// let a = net_io::monotonic_micros();
46/// let b = net_io::monotonic_micros();
47/// assert!(b >= a);
48/// ```
49#[must_use]
50pub fn monotonic_micros() -> u64 {
51    crate::sys::monotonic_micros()
52}
53
54impl Clock for MonotonicClock {
55    #[inline]
56    fn now(&self) -> Instant {
57        Instant::now()
58    }
59}
60
61/// A clock that moves only when told to, for deterministic timeout tests.
62///
63/// ```
64/// use net_io::{Clock, ManualClock};
65/// use std::time::Duration;
66/// let clock = ManualClock::new();
67/// let start = clock.now();
68/// clock.advance(Duration::from_secs(61));
69/// assert_eq!(clock.now() - start, Duration::from_secs(61));
70/// ```
71#[derive(Debug)]
72pub struct ManualClock {
73    now: Mutex<Instant>,
74}
75
76impl ManualClock {
77    /// A clock frozen at the current instant.
78    #[must_use]
79    pub fn new() -> ManualClock {
80        ManualClock {
81            now: Mutex::new(Instant::now()),
82        }
83    }
84
85    /// Moves the clock forward.
86    pub fn advance(&self, by: Duration) {
87        let mut now = self.now.lock().unwrap_or_else(PoisonError::into_inner);
88        *now = now.checked_add(by).unwrap_or(*now);
89    }
90
91    /// Moves the clock to `at`; never backwards.
92    ///
93    /// ```
94    /// use net_io::{Clock, ManualClock};
95    /// let clock = ManualClock::new();
96    /// let t = clock.now();
97    /// clock.set(t - std::time::Duration::from_secs(1));
98    /// assert_eq!(clock.now(), t);
99    /// ```
100    pub fn set(&self, at: Instant) {
101        let mut now = self.now.lock().unwrap_or_else(PoisonError::into_inner);
102        if at > *now {
103            *now = at;
104        }
105    }
106}
107
108impl Default for ManualClock {
109    fn default() -> ManualClock {
110        ManualClock::new()
111    }
112}
113
114impl Clock for ManualClock {
115    fn now(&self) -> Instant {
116        *self.now.lock().unwrap_or_else(PoisonError::into_inner)
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn test_manual_clock_frozen_until_advanced() {
126        let c = ManualClock::new();
127        let a = c.now();
128        std::thread::sleep(Duration::from_millis(2));
129        assert_eq!(c.now(), a);
130        c.advance(Duration::from_millis(5));
131        assert_eq!(c.now(), a + Duration::from_millis(5));
132    }
133
134    #[test]
135    fn test_manual_clock_set_forward_only() {
136        let c = ManualClock::new();
137        let a = c.now();
138        c.set(a + Duration::from_secs(3));
139        c.set(a);
140        assert_eq!(c.now(), a + Duration::from_secs(3));
141    }
142}