Skip to main content

maybenot/
time.rs

1use std::ops::AddAssign;
2
3/// Trait representing instants in time. Allows using maybenot frameworks with
4/// custom time sources. If you want to use maybenot with a different time source
5/// than `std::time::Instant`, implement this trait for your instant type, and the
6/// [`Duration`] trait for your corresponding duration type.
7pub trait Instant: Clone + Copy {
8    type Duration: Duration;
9
10    /// Returns the amount of time elapsed from another instant to this one.
11    ///
12    /// Should return a zero duration if `earlier` is later than `self`
13    fn saturating_duration_since(&self, earlier: Self) -> Self::Duration;
14}
15
16pub trait Duration: Clone + Copy + AddAssign + PartialOrd {
17    /// Creates a new duration, spanning no time.
18    fn zero() -> Self;
19
20    /// Creates a new duration from the specified number of microseconds.
21    fn from_micros(micros: u64) -> Self;
22
23    /// Returns true if this duration spans no time.
24    fn is_zero(&self) -> bool;
25
26    /// Divide this duration by another Duration and return f64.
27    fn div_duration_f64(self, rhs: Self) -> f64;
28}
29
30impl Instant for std::time::Instant {
31    type Duration = std::time::Duration;
32
33    #[inline(always)]
34    fn saturating_duration_since(&self, earlier: Self) -> Self::Duration {
35        self.saturating_duration_since(earlier)
36    }
37}
38
39impl Duration for std::time::Duration {
40    #[inline(always)]
41    fn zero() -> Self {
42        Self::ZERO
43    }
44
45    #[inline(always)]
46    fn from_micros(micros: u64) -> Self {
47        Self::from_micros(micros)
48    }
49
50    #[inline(always)]
51    fn is_zero(&self) -> bool {
52        self.is_zero()
53    }
54
55    #[inline(always)]
56    fn div_duration_f64(self, rhs: Self) -> f64 {
57        self.div_duration_f64(rhs)
58    }
59}