cap_time_ext/
system_clock.rs

1#[cfg(not(windows))]
2use rustix::time::{clock_getres, ClockId};
3use std::time::{self, Duration};
4
5/// Extension trait for `cap_std::time::SystemClock`.
6pub trait SystemClockExt {
7    /// A system clock datapoint.
8    type SystemTime;
9
10    /// Similar to `SystemClock::now`, but takes an additional `precision`
11    /// parameter allowing callers to inform the implementation when they
12    /// don't need full precision. The implementation need not make any
13    /// effort to provide a time with greater precision.
14    fn now_with(&self, precision: Duration) -> Self::SystemTime;
15
16    /// Return the resolution of the clock.
17    fn resolution(&self) -> Duration;
18}
19
20#[cfg(not(windows))]
21impl SystemClockExt for cap_primitives::time::SystemClock {
22    type SystemTime = cap_primitives::time::SystemTime;
23
24    #[cfg(not(target_os = "wasi"))]
25    #[inline]
26    fn now_with(&self, _precision: Duration) -> Self::SystemTime {
27        // On systems with no optimized form of `clock_gettime`, ignore the
28        // precision argument.
29        Self::SystemTime::from_std(time::SystemTime::now())
30    }
31
32    fn resolution(&self) -> Duration {
33        let spec = clock_getres(ClockId::Realtime);
34        Duration::new(
35            spec.tv_sec.try_into().unwrap(),
36            spec.tv_nsec.try_into().unwrap(),
37        )
38    }
39}
40
41#[cfg(windows)]
42impl SystemClockExt for cap_primitives::time::SystemClock {
43    type SystemTime = cap_primitives::time::SystemTime;
44
45    #[inline]
46    fn now_with(&self, _precision: Duration) -> Self::SystemTime {
47        // On systems with no optimized form of `clock_gettime`, ignore the
48        // precision argument.
49        Self::SystemTime::from_std(time::SystemTime::now())
50    }
51
52    fn resolution(&self) -> Duration {
53        // According to [this blog post], the system timer resolution is 55ms
54        // or 10ms. Use the more conservative of the two.
55        //
56        // [this blog post]: https://devblogs.microsoft.com/oldnewthing/20170921-00/?p=97057
57        Duration::new(0, 55_000_000)
58    }
59}