Skip to main content

t2t_clock/
clock.rs

1//! The one verb every clock answers.
2
3/// A clock: what time it is now.
4///
5/// The type a clock reads says which timeline its readings are on, so readings of two timelines
6/// never mix: a point for a clock that names a moment, and a span for one that counts CPU time.
7///
8/// # Examples
9/// ```
10/// use core::cell::Cell;
11///
12/// use t2t_clock::Clock;
13/// use t2t_core::Tickstamp;
14///
15/// /// A clock that moves one tick at each reading.
16/// struct StepClock(Cell<i64>);
17///
18/// impl Clock for StepClock {
19///     type Reading = Tickstamp;
20///
21///     fn now(&self) -> Tickstamp {
22///         self.0.set(self.0.get() + 1);
23///         Tickstamp::from_ticks(self.0.get())
24///     }
25/// }
26///
27/// let clock = StepClock(Cell::new(0));
28/// assert!(clock.now() < clock.now(), "each reading later than the last");
29/// ```
30pub trait Clock {
31    /// What the clock reads.
32    type Reading: Copy;
33
34    /// The time now.
35    #[must_use]
36    fn now(&self) -> Self::Reading;
37}
38
39impl<C: Clock + ?Sized> Clock for &C {
40    type Reading = C::Reading;
41
42    #[inline]
43    fn now(&self) -> Self::Reading {
44        (**self).now()
45    }
46}