oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `time` on WASI: `clock_time_get`, `clock_res_get`, and `poll_oneoff` to
//! sleep.

use core::time::Duration;

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

// `clockid`.
const CLOCK_REALTIME: i32 = 0;
const CLOCK_MONOTONIC: i32 = 1;
const CLOCK_PROCESS_CPUTIME: i32 = 2;
const CLOCK_THREAD_CPUTIME: i32 = 3;

/// `eventtype::clock`, the tag of a clock subscription.
const EVENTTYPE_CLOCK: u8 = 0;

/// `subscription`, in its `clock` variant: the largest of the union.
#[repr(C)]
struct Subscription {
    userdata: u64,
    tag: u8,
    /// The union starts at its own alignment, 8.
    padding: [u8; 7],
    clock_id: u32,
    timeout: u64,
    precision: u64,
    flags: u16,
}

/// `event`.
#[repr(C)]
#[derive(Default)]
struct Event {
    userdata: u64,
    error: u16,
    kind: u8,
    nbytes: u64,
    flags: u16,
}

// The layouts of the witx definition.
const _: () = {
    assert!(size_of::<Subscription>() == 48);
    assert!(core::mem::offset_of!(Subscription, clock_id) == 16);
    assert!(core::mem::offset_of!(Subscription, timeout) == 24);
    assert!(core::mem::offset_of!(Subscription, flags) == 40);
    assert!(size_of::<Event>() == 32);
    assert!(core::mem::offset_of!(Event, nbytes) == 16);
};

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn clock_time_get(id: i32, precision: i64, time: *mut u64) -> i32;
    fn clock_res_get(id: i32, resolution: *mut u64) -> i32;
    fn poll_oneoff(
        subscriptions: *const Subscription,
        events: *mut Event,
        count: usize,
        stored: *mut usize,
    ) -> i32;
}

fn gettime(id: i32) -> Result<u64> {
    let mut nanos = 0;
    // SAFETY: the host writes one `u64`.
    cvt(unsafe { clock_time_get(id, 1, &raw mut nanos) })?;
    Ok(nanos)
}

fn clock_id(clock: Clock) -> Result<i32> {
    match clock {
        Clock::Monotonic => Ok(CLOCK_MONOTONIC),
        Clock::Boottime => Err(ErrorKind::Unsupported.into()),
        Clock::ProcessCpu => Ok(CLOCK_PROCESS_CPUTIME),
        Clock::ThreadCpu => Ok(CLOCK_THREAD_CPUTIME),
    }
}

pub(crate) fn now() -> Result<Timestamp> {
    let nanos = gettime(CLOCK_REALTIME)?;
    Ok(Timestamp {
        secs: (nanos / 1_000_000_000) as i64,
        nanos: (nanos % 1_000_000_000) as u32,
    })
}

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

pub(crate) fn resolution(clock: Clock) -> Result<Duration> {
    let mut nanos = 0;
    // SAFETY: the host writes one `u64`.
    cvt(unsafe { clock_res_get(clock_id(clock)?, &raw mut nanos) })?;
    Ok(Duration::from_nanos(nanos))
}

/// Sleeps until the monotonic clock reaches `deadline`, in nanoseconds.
///
/// This loops, checking the clock: hosts are free to round the timeout of
/// `poll_oneoff`, and some round it down (Node, to a millisecond).
fn sleep_until_nanos(deadline: u64) -> Result<()> {
    loop {
        let now = gettime(CLOCK_MONOTONIC)?;
        if now >= deadline {
            return Ok(());
        }
        let subscription = Subscription {
            userdata: 0,
            tag: EVENTTYPE_CLOCK,
            padding: [0; 7],
            clock_id: CLOCK_MONOTONIC as u32,
            timeout: deadline - now,
            precision: 0,
            flags: 0,
        };
        let mut event = Event::default();
        let mut stored = 0;
        // SAFETY: the host reads one subscription and writes at most one
        // event, and the count of events stored.
        cvt(unsafe { poll_oneoff(&raw const subscription, &raw mut event, 1, &raw mut stored) })?;
        if stored == 1 && event.error != 0 {
            return Err(Error::from_raw_os_error(event.error.into()));
        }
    }
}

fn to_nanos(duration: Duration) -> u64 {
    u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
}

pub(crate) fn sleep(duration: Duration) -> Result<()> {
    sleep_until_nanos(gettime(CLOCK_MONOTONIC)?.saturating_add(to_nanos(duration)))
}

pub(crate) fn sleep_until(deadline: Duration) -> Result<()> {
    sleep_until_nanos(to_nanos(deadline))
}