use crate::{shm::ShmError, syserror};
use nix::sys::time::TimeSpec;
use nix::time::{ClockId, clock_gettime};
pub const CLOCK_REALTIME: ClockId = ClockId::CLOCK_REALTIME;
#[cfg(target_os = "macos")]
pub const CLOCK_MONOTONIC: ClockId = ClockId::CLOCK_MONOTONIC;
#[cfg(not(target_os = "macos"))]
pub const CLOCK_MONOTONIC: ClockId = ClockId::CLOCK_MONOTONIC_COARSE;
#[expect(clippy::missing_errors_doc, reason = "todo")]
pub fn clock_gettime_safe(clock_id: ClockId) -> Result<TimeSpec, ShmError> {
match clock_gettime(clock_id) {
Ok(ts) => Ok(ts),
_ => syserror!(String::from("clock_gettime failed")),
}
}
#[cfg(test)]
mod t_common {
use super::*;
use std::{thread, time};
#[test]
fn clock_gettime_safe_realtime() {
let one = clock_gettime_safe(CLOCK_REALTIME).expect("Failed on clock_gettime");
thread::sleep(time::Duration::from_millis(10));
let two = clock_gettime_safe(CLOCK_REALTIME).expect("Failed on clock_gettime");
assert!(two > one);
}
#[test]
fn clock_gettime_safe_monotonic() {
let one = clock_gettime_safe(CLOCK_MONOTONIC).expect("Failed on clock_gettime");
thread::sleep(time::Duration::from_millis(11));
let two = clock_gettime_safe(CLOCK_MONOTONIC).expect("Failed on clock_gettime");
assert!(two > one);
}
}