clocksource/sys/
unix.rs

1#[cfg(any(target_os = "macos", target_os = "ios"))]
2const CLOCK_MONOTONIC_COARSE: u32 = libc::CLOCK_MONOTONIC;
3
4#[cfg(not(any(target_os = "macos", target_os = "ios")))]
5const CLOCK_MONOTONIC_COARSE: i32 = libc::CLOCK_MONOTONIC_COARSE;
6
7#[cfg(any(target_os = "macos", target_os = "ios"))]
8const CLOCK_REALTIME_COARSE: u32 = libc::CLOCK_REALTIME;
9
10#[cfg(not(any(target_os = "macos", target_os = "ios")))]
11const CLOCK_REALTIME_COARSE: i32 = libc::CLOCK_REALTIME_COARSE;
12
13pub fn read_clock(clock: i32) -> libc::timespec {
14    let mut ts = libc::timespec {
15        tv_sec: 0,
16        tv_nsec: 0,
17    };
18
19    unsafe {
20        libc::clock_gettime(clock as _, &mut ts);
21    }
22
23    ts
24}
25
26pub mod monotonic {
27    use super::*;
28
29    pub fn coarse() -> crate::coarse::Instant {
30        let ts = read_clock(CLOCK_MONOTONIC_COARSE as _);
31
32        let now = ts.tv_sec as u32;
33
34        crate::coarse::Instant { secs: now }
35    }
36
37    pub fn precise() -> crate::precise::Instant {
38        let ts = read_clock(libc::CLOCK_MONOTONIC as _);
39
40        let now = (ts.tv_sec as u64)
41            .wrapping_mul(1_000_000_000)
42            .wrapping_add(ts.tv_nsec as u64);
43
44        crate::precise::Instant { ns: now }
45    }
46}
47
48pub mod realtime {
49    use super::*;
50
51    pub fn coarse() -> crate::coarse::UnixInstant {
52        let ts = read_clock(CLOCK_REALTIME_COARSE as _);
53
54        let now = ts.tv_sec as u32;
55
56        crate::coarse::UnixInstant { secs: now }
57    }
58
59    pub fn precise() -> crate::precise::UnixInstant {
60        let ts = read_clock(libc::CLOCK_REALTIME as _);
61
62        let now = (ts.tv_sec as u64)
63            .wrapping_mul(1_000_000_000)
64            .wrapping_add(ts.tv_nsec as u64);
65
66        crate::precise::UnixInstant { ns: now }
67    }
68}