oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `sync` on Windows: `WaitOnAddress` and `WakeByAddress*`.

use core::ffi::c_void;
use core::sync::atomic::AtomicU32;
use core::time::Duration;

use crate::Result;
use crate::sys::time::{to_units, unbiased};
use crate::sys::{dll, last_error};

const INFINITE: u32 = u32::MAX;
const ERROR_TIMEOUT: i32 = 1460;

// kernel32 does not export these: they live in the API set, which resolves
// to kernelbase.dll.
dll!("api-ms-win-core-synch-l1-2-0.dll" {
    fn WaitOnAddress(
        address: *const c_void,
        compare: *const c_void,
        size: usize,
        milliseconds: u32,
    ) -> i32;
    fn WakeByAddressSingle(address: *const c_void);
    fn WakeByAddressAll(address: *const c_void);
});

/// Whether the wait ended otherwise than by its timeout.
pub(crate) fn wait(atomic: &AtomicU32, expected: u32, timeout: Option<Duration>) -> Result<bool> {
    // `deadline` is on the unbiased interrupt time, the clock
    // `Clock::Monotonic` reads; `None` when there is no timeout to honour.
    let (milliseconds, deadline) = match timeout {
        None => (INFINITE, None),
        Some(timeout) => {
            let ms = timeout.as_nanos().div_ceil(1_000_000);
            match u32::try_from(ms) {
                Ok(ms) if ms != INFINITE => {
                    (ms, Some(unbiased().saturating_add(to_units(timeout))))
                }
                // More than the 49 days the function counts.
                _ => (INFINITE - 1, None),
            }
        }
    };
    // SAFETY: the function reads four bytes at each address: the atomic,
    // which is borrowed, and `expected`.
    let woken = unsafe {
        WaitOnAddress(
            atomic.as_ptr().cast(),
            (&raw const expected).cast(),
            size_of::<u32>(),
            milliseconds,
        )
    };
    if woken != 0 {
        // Woken, or the value was not the expected one.
        return Ok(true);
    }
    let error = last_error();
    if error.raw_os_error() == ERROR_TIMEOUT {
        // The function counts in timer ticks, and reports its timeout up to
        // one tick early (and after 49 days if it was shortened). A timeout
        // that has not really passed is a spurious wake-up: the caller
        // waits again for what is left.
        Ok(deadline.is_none_or(|deadline| unbiased() < deadline))
    } else {
        Err(error)
    }
}

pub(crate) fn wake(atomic: &AtomicU32, all: bool) {
    let address = atomic.as_ptr().cast::<c_void>().cast_const();
    // SAFETY: the functions only use the address as a key.
    unsafe {
        if all {
            WakeByAddressAll(address);
        } else {
            WakeByAddressSingle(address);
        }
    }
}