oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `time` on macOS: `clock_gettime`, `clock_getres` and `nanosleep`.

use core::ffi::{c_int, c_long};
use core::time::Duration;

use crate::sys::cvt;
use crate::time::{Clock, Timestamp};
use crate::{ErrorKind, Result};

// <time.h>
const CLOCK_REALTIME: c_int = 0;
const CLOCK_MONOTONIC_RAW: c_int = 4;
const CLOCK_UPTIME_RAW: c_int = 8;
const CLOCK_PROCESS_CPUTIME_ID: c_int = 12;
const CLOCK_THREAD_CPUTIME_ID: c_int = 16;

/// The longest sleep asked of the kernel, which adds it to its own clock:
/// 136 years.
const MAX_SLEEP_SECS: u64 = u32::MAX as u64;

/// `struct timespec`.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Timespec {
    sec: i64,
    nsec: c_long,
}

unsafe extern "C" {
    fn clock_gettime(id: c_int, ts: *mut Timespec) -> c_int;
    fn clock_getres(id: c_int, ts: *mut Timespec) -> c_int;
    fn nanosleep(request: *const Timespec, remaining: *mut Timespec) -> c_int;
}

impl Timespec {
    fn to_duration(self) -> Result<Duration> {
        match (u64::try_from(self.sec), u32::try_from(self.nsec)) {
            (Ok(sec), Ok(nsec)) if nsec < 1_000_000_000 => Ok(Duration::new(sec, nsec)),
            _ => Err(ErrorKind::Other.into()),
        }
    }
}

fn gettime(id: c_int) -> Result<Timespec> {
    let mut ts = Timespec::default();
    // SAFETY: the function writes one `timespec` to `ts`.
    cvt(unsafe { clock_gettime(id, &raw mut ts) })?;
    Ok(ts)
}

fn clock_id(clock: Clock) -> c_int {
    match clock {
        Clock::Monotonic => CLOCK_UPTIME_RAW,
        Clock::Boottime => CLOCK_MONOTONIC_RAW,
        Clock::ProcessCpu => CLOCK_PROCESS_CPUTIME_ID,
        Clock::ThreadCpu => CLOCK_THREAD_CPUTIME_ID,
    }
}

pub(crate) fn now() -> Result<Timestamp> {
    let ts = gettime(CLOCK_REALTIME)?;
    match u32::try_from(ts.nsec) {
        Ok(nanos) if nanos < 1_000_000_000 => Ok(Timestamp {
            secs: ts.sec,
            nanos,
        }),
        _ => Err(ErrorKind::Other.into()),
    }
}

pub(crate) fn clock(clock: Clock) -> Result<Duration> {
    gettime(clock_id(clock))?.to_duration()
}

pub(crate) fn resolution(clock: Clock) -> Result<Duration> {
    let mut ts = Timespec::default();
    // SAFETY: the function writes one `timespec` to `ts`.
    cvt(unsafe { clock_getres(clock_id(clock), &raw mut ts) })?;
    ts.to_duration()
}

pub(crate) fn sleep(duration: Duration) -> Result<()> {
    let ts = Timespec {
        sec: duration.as_secs().min(MAX_SLEEP_SECS) as i64,
        nsec: duration.subsec_nanos() as c_long,
    };
    // SAFETY: the function reads one `timespec`; no remaining time is asked
    // for.
    cvt(unsafe { nanosleep(&raw const ts, core::ptr::null_mut()) })?;
    Ok(())
}

pub(crate) fn sleep_until(deadline: Duration) -> Result<()> {
    match deadline.checked_sub(clock(Clock::Monotonic)?) {
        Some(left) if !left.is_zero() => sleep(left),
        _ => Ok(()),
    }
}