1use std::fmt;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::Duration;
11
12use jiff::{SignedDuration, Timestamp};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct Instant {
22 nanos: u64,
23}
24
25impl Instant {
26 pub(crate) const fn from_nanos(nanos: u64) -> Self {
28 Self { nanos }
29 }
30
31 pub(crate) const fn as_nanos(self) -> u64 {
33 self.nanos
34 }
35
36 #[must_use]
38 pub const fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
39 match self.nanos.checked_sub(earlier.nanos) {
40 Some(nanos) => Some(Duration::from_nanos(nanos)),
41 None => None,
42 }
43 }
44
45 #[must_use]
47 pub const fn duration_since(self, earlier: Self) -> Duration {
48 Duration::from_nanos(self.nanos.saturating_sub(earlier.nanos))
49 }
50
51 #[must_use]
53 pub fn checked_add(self, by: Duration) -> Option<Self> {
54 let nanos = u64::try_from(by.as_nanos()).ok()?;
55 self.nanos.checked_add(nanos).map(Self::from_nanos)
56 }
57
58 #[must_use]
60 pub fn checked_sub(self, by: Duration) -> Option<Self> {
61 let nanos = u64::try_from(by.as_nanos()).ok()?;
62 self.nanos.checked_sub(nanos).map(Self::from_nanos)
63 }
64}
65
66pub trait Clock: Send + Sync + 'static {
68 fn now(&self) -> Instant;
70
71 fn utc_now(&self) -> Timestamp;
74}
75
76#[derive(Debug, Clone, Copy, Default)]
84pub struct SystemClock;
85
86impl Clock for SystemClock {
87 fn now(&self) -> Instant {
88 Instant::from_nanos(system_nanos())
89 }
90
91 fn utc_now(&self) -> Timestamp {
92 Timestamp::now()
93 }
94}
95
96#[cfg(any(target_os = "linux", target_os = "android"))]
97const SYSTEM_CLOCK: rustix::time::ClockId = rustix::time::ClockId::Boottime;
98
99#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
100const SYSTEM_CLOCK: rustix::time::ClockId = rustix::time::ClockId::Monotonic;
101
102#[cfg(unix)]
103fn system_nanos() -> u64 {
104 let now = rustix::time::clock_gettime(SYSTEM_CLOCK);
105 let secs = u64::try_from(now.tv_sec).expect("the system clock is not negative");
106 let subsec = u64::try_from(now.tv_nsec).expect("tv_nsec is not negative");
107 secs.checked_mul(1_000_000_000)
108 .and_then(|nanos| nanos.checked_add(subsec))
109 .expect("the system clock fits in u64 nanoseconds")
110}
111
112#[cfg(windows)]
113fn system_nanos() -> u64 {
114 let mut ticks = 0_u64;
115 unsafe { windows_sys::Win32::System::WindowsProgramming::QueryInterruptTime(&raw mut ticks) };
117 ticks
119 .checked_mul(100)
120 .expect("the interrupt time fits in u64 nanoseconds")
121}
122
123#[derive(Debug, Clone)]
128pub struct ManualClock {
129 advanced_nanos: Arc<AtomicU64>,
130 origin_utc: Timestamp,
131}
132
133impl ManualClock {
134 #[must_use]
136 pub fn new() -> Self {
137 Self::at_utc(Timestamp::UNIX_EPOCH)
138 }
139
140 #[must_use]
143 pub fn at_utc(origin_utc: Timestamp) -> Self {
144 Self {
145 advanced_nanos: Arc::new(AtomicU64::new(0)),
146 origin_utc,
147 }
148 }
149
150 pub fn advance(&self, by: Duration) {
156 let nanos = u64::try_from(by.as_nanos()).expect("advance fits in u64 nanoseconds");
157 self.advanced_nanos.fetch_add(nanos, Ordering::Relaxed);
158 }
159}
160
161impl Default for ManualClock {
162 fn default() -> Self {
163 Self::new()
164 }
165}
166
167impl Clock for ManualClock {
168 fn now(&self) -> Instant {
169 Instant::from_nanos(self.advanced_nanos.load(Ordering::Relaxed))
170 }
171
172 fn utc_now(&self) -> Timestamp {
173 let advanced = i64::try_from(self.advanced_nanos.load(Ordering::Relaxed))
174 .expect("a manual clock stays within i64 nanoseconds");
175 self.origin_utc
176 .checked_add(SignedDuration::from_nanos(advanced))
177 .expect("a manual clock stays within the timestamp range")
178 }
179}
180
181#[derive(Clone)]
186pub struct AnyClock(Arc<dyn Clock>);
187
188impl AnyClock {
189 #[must_use]
191 pub fn new(clock: impl Clock) -> Self {
192 Self(Arc::new(clock))
193 }
194
195 #[must_use]
197 pub fn now(&self) -> Instant {
198 self.0.now()
199 }
200
201 #[must_use]
203 pub fn utc_now(&self) -> Timestamp {
204 self.0.utc_now()
205 }
206
207 #[must_use]
209 pub fn since(&self, earlier: Instant) -> Duration {
210 self.now().duration_since(earlier)
211 }
212}
213
214impl Default for AnyClock {
215 fn default() -> Self {
216 Self::new(SystemClock)
217 }
218}
219
220impl fmt::Debug for AnyClock {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.write_str("AnyClock")
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn the_system_clock_advances() {
232 let clock = SystemClock;
233 let first = clock.now();
234 std::thread::sleep(Duration::from_millis(20));
235 assert!(clock.now().duration_since(first) >= Duration::from_millis(20));
236 }
237
238 #[test]
239 fn instants_do_arithmetic() {
240 let at = Instant::from_nanos(10_000);
241 let later = at.checked_add(Duration::from_micros(5)).unwrap();
242 assert_eq!(later.duration_since(at), Duration::from_micros(5));
243 assert_eq!(at.duration_since(later), Duration::ZERO);
244 assert_eq!(at.checked_duration_since(later), None);
245 assert_eq!(later.checked_sub(Duration::from_micros(5)), Some(at));
246 assert_eq!(at.checked_sub(Duration::from_secs(1)), None);
247 }
248}