quanta/clocks/monotonic/
unix.rs

1#[derive(Clone, Copy, Debug, Default)]
2pub struct Monotonic {
3    _default: (),
4}
5
6impl Monotonic {
7    #[allow(clippy::cast_sign_loss)]
8    pub fn now(self) -> u64 {
9        let mut ts = libc::timespec {
10            tv_sec: 0,
11            tv_nsec: 0,
12        };
13        unsafe {
14            libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
15        }
16
17        // LINT JUSTIFICATION:
18        //
19        // We really don't ever expect to actually _get_ negative values from `clock_gettime`, but
20        // given the types, it's technically possible.  This is due to the fact that `tv_sec` is
21        // supposed to be `time_t`, which Unix/POSIX-compliant systems implement as a signed number.
22        // Accordingly, `tv_nsec` follows suit using a signed number.
23        //
24        // Given the adjustments made by NTP to clocks like CLOCK_MONOTONIC, and that
25        // CLOCK_MONOTONIC can be anchored to an arbitrary point, and a whole skew of other
26        // scenarios where it could be modified... it's technicaly possible to get back valid
27        // negative values.  If we did math between `timespec` objects, the delta should be valid,
28        // even with negative numbers.
29        //
30        // We're returning a u64 here, though, so it is what it is.  In practice, I've _never_ seen
31        // negative values under normal operation.  If someone discovers a valid scenario where this
32        // is violated and that we need to account for, I'll be colored impressed, but also, file an
33        // issue and we'll do what we have to do to rework the code to try and support it better.
34        //
35        // Until then, though, we're just gonna ignore the lint.
36        ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64
37    }
38}