moka2/common/
time.rs

1use std::time::Duration;
2
3#[cfg_attr(feature = "quanta", path = "time/clock_quanta.rs")]
4#[cfg_attr(not(feature = "quanta"), path = "time/clock_compat.rs")]
5pub(crate) mod clock;
6
7pub(crate) use clock::Clock;
8
9#[cfg(test)]
10pub(crate) use clock::Mock;
11
12/// a wrapper type over Instant to force checked additions and prevent
13/// unintentional overflow. The type preserve the Copy semantics for the wrapped
14#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
15pub(crate) struct Instant(clock::Instant);
16
17pub(crate) trait CheckedTimeOps {
18    fn checked_add(&self, duration: Duration) -> Option<Self>
19    where
20        Self: Sized;
21
22    fn checked_duration_since(&self, earlier: Self) -> Option<Duration>
23    where
24        Self: Sized;
25}
26
27impl Instant {
28    pub(crate) fn new(instant: clock::Instant) -> Instant {
29        Instant(instant)
30    }
31
32    pub(crate) fn now() -> Instant {
33        Instant(clock::Instant::now())
34    }
35
36    #[cfg(feature = "quanta")]
37    pub(crate) fn inner_clock(self) -> clock::Instant {
38        self.0
39    }
40}
41
42impl CheckedTimeOps for Instant {
43    fn checked_add(&self, duration: Duration) -> Option<Instant> {
44        self.0.checked_add(duration).map(Instant)
45    }
46
47    fn checked_duration_since(&self, earlier: Self) -> Option<Duration>
48    where
49        Self: Sized,
50    {
51        self.0.checked_duration_since(earlier.0)
52    }
53}