Skip to main content

syncopate/clock/
instant.rs

1use std::time::Duration;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4pub struct MonoInstant(pub u64);
5
6impl MonoInstant {
7    pub const ZERO: Self = Self(0);
8
9    #[inline]
10    pub fn as_nanos(self) -> u64 {
11        self.0
12    }
13
14    #[inline]
15    pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
16        self.0.checked_sub(earlier.0).map(Duration::from_nanos)
17    }
18
19    #[inline]
20    pub fn saturating_duration_since(self, earlier: Self) -> Duration {
21        Duration::from_nanos(self.0.saturating_sub(earlier.0))
22    }
23}
24
25impl std::ops::Add<Duration> for MonoInstant {
26    type Output = Self;
27    fn add(self, rhs: Duration) -> Self {
28        Self(self.0.saturating_add(rhs.as_nanos() as u64))
29    }
30}
31
32impl std::ops::AddAssign<Duration> for MonoInstant {
33    fn add_assign(&mut self, rhs: Duration) {
34        *self = *self + rhs;
35    }
36}
37
38impl std::ops::Sub<Duration> for MonoInstant {
39    type Output = Self;
40    fn sub(self, rhs: Duration) -> Self {
41        Self(self.0.saturating_sub(rhs.as_nanos() as u64))
42    }
43}
44
45impl std::ops::Sub<MonoInstant> for MonoInstant {
46    type Output = Duration;
47    fn sub(self, rhs: MonoInstant) -> Duration {
48        self.saturating_duration_since(rhs)
49    }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
53pub struct WallInstant(pub u64);
54
55impl WallInstant {
56    pub const UNIX_EPOCH: Self = Self(0);
57
58    #[inline]
59    pub fn as_nanos(self) -> u64 {
60        self.0
61    }
62
63    #[inline]
64    pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
65        self.0.checked_sub(earlier.0).map(Duration::from_nanos)
66    }
67
68    #[inline]
69    pub fn saturating_duration_since(self, earlier: Self) -> Duration {
70        Duration::from_nanos(self.0.saturating_sub(earlier.0))
71    }
72}
73
74impl std::ops::Add<Duration> for WallInstant {
75    type Output = Self;
76    fn add(self, rhs: Duration) -> Self {
77        Self(self.0.saturating_add(rhs.as_nanos() as u64))
78    }
79}
80
81impl std::ops::AddAssign<Duration> for WallInstant {
82    fn add_assign(&mut self, rhs: Duration) {
83        *self = *self + rhs;
84    }
85}
86
87impl std::ops::Sub<Duration> for WallInstant {
88    type Output = Self;
89    fn sub(self, rhs: Duration) -> Self {
90        Self(self.0.saturating_sub(rhs.as_nanos() as u64))
91    }
92}
93
94impl std::ops::Sub<WallInstant> for WallInstant {
95    type Output = Duration;
96    fn sub(self, rhs: WallInstant) -> Duration {
97        self.saturating_duration_since(rhs)
98    }
99}