clock_bound_shm/
common.rs

1use crate::{syserror, ShmError};
2use nix::sys::time::TimeSpec;
3use nix::time::{clock_gettime, ClockId};
4
5pub const CLOCK_REALTIME: ClockId = ClockId::CLOCK_REALTIME;
6
7// This primarily for development convenience
8#[cfg(target_os = "macos")]
9pub const CLOCK_MONOTONIC: ClockId = ClockId::CLOCK_MONOTONIC;
10#[cfg(not(target_os = "macos"))]
11pub const CLOCK_MONOTONIC: ClockId = ClockId::CLOCK_MONOTONIC_COARSE;
12
13/// Read a specific view of time
14///
15/// This function wraps the `clock_gettime()` system call to conveniently return the current time
16/// tracked by a specific clock.
17///
18/// The clock_id is one of ClockId::CLOCK_REALTIME, ClockId::CLOCK_MONOTONIC, etc.
19pub fn clock_gettime_safe(clock_id: ClockId) -> Result<TimeSpec, ShmError> {
20    match clock_gettime(clock_id) {
21        Ok(ts) => Ok(ts),
22        _ => syserror!("clock_gettime"),
23    }
24}
25
26#[cfg(test)]
27mod t_common {
28    use super::*;
29    use std::{thread, time};
30
31    /// Assert that clock_gettime(REALTIME) is functional (naive test)
32    #[test]
33    fn clock_gettime_safe_realtime() {
34        let one = clock_gettime_safe(CLOCK_REALTIME).expect("Failed on clock_gettime");
35        // Sleep a bit, some platform (macos) have a low res
36        thread::sleep(time::Duration::from_millis(10));
37        let two = clock_gettime_safe(CLOCK_REALTIME).expect("Failed on clock_gettime");
38
39        assert!(two > one);
40    }
41
42    /// Assert that clock_gettime(MONOTONIC) is functional (naive test)
43    #[test]
44    fn clock_gettime_safe_monotonic() {
45        let one = clock_gettime_safe(CLOCK_MONOTONIC).expect("Failed on clock_gettime");
46        // Clock resolution for CLOCK_MONOTONIC_COARSE on
47        // Amazon Linux 2 x86_64 on c5.4xlarge is 10 milliseconds.
48        // Sleep an amount larger than that clock resolution.
49        thread::sleep(time::Duration::from_millis(11));
50        let two = clock_gettime_safe(CLOCK_MONOTONIC).expect("Failed on clock_gettime");
51
52        assert!(two > one);
53    }
54}