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
//! `event` on Windows: `WSAPoll`.
//!
//! Constants and layouts are those of `<winsock2.h>`.

use core::time::Duration;

use crate::event::{Interest, Readiness};
use crate::sys::dll;
use crate::sys::net::RawSocket;
use crate::sys::time::{to_units, unbiased};
use crate::{Error, Result};

const POLLERR: i16 = 0x0001;
const POLLHUP: i16 = 0x0002;
const POLLNVAL: i16 = 0x0004;
const POLLWRNORM: i16 = 0x0010;
const POLLRDNORM: i16 = 0x0100;
const POLLRDBAND: i16 = 0x0200;

const SOCKET_ERROR: i32 = -1;
/// The interrupt time counts in units of 100 ns.
const UNITS_PER_MS: u64 = 10_000;

/// `WSAPOLLFD`.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct PollFd {
    fd: usize,
    events: i16,
    revents: i16,
}

dll!("ws2_32.dll" {
    fn WSAPoll(fds: *mut PollFd, count: u32, timeout: i32) -> i32;
    fn WSAGetLastError() -> i32;
});

/// The calling thread's last Winsock error.
fn wsa_error() -> Error {
    // SAFETY: WSAGetLastError only reads thread-local state.
    Error::from_raw_os_error(unsafe { WSAGetLastError() })
}

impl PollFd {
    pub(crate) fn new(fd: RawSocket, interest: Interest) -> Self {
        let mut events = 0;
        if interest.contains(Interest::READABLE) {
            events |= POLLRDNORM;
        }
        if interest.contains(Interest::WRITABLE) {
            events |= POLLWRNORM;
        }
        Self {
            fd,
            events,
            revents: 0,
        }
    }

    pub(crate) fn raw(&self) -> RawSocket {
        self.fd
    }

    pub(crate) fn interest(&self) -> Interest {
        let mut interest = Interest::empty();
        if self.events & POLLRDNORM != 0 {
            interest |= Interest::READABLE;
        }
        if self.events & POLLWRNORM != 0 {
            interest |= Interest::WRITABLE;
        }
        interest
    }

    pub(crate) fn readiness(&self) -> Readiness {
        let mut readiness = Readiness::empty();
        for (bit, flag) in [
            (POLLRDNORM | POLLRDBAND, Readiness::READABLE),
            (POLLWRNORM, Readiness::WRITABLE),
            (POLLERR, Readiness::ERROR),
            (POLLHUP, Readiness::HANGUP),
            (POLLNVAL, Readiness::INVALID),
        ] {
            if self.revents & bit != 0 {
                readiness |= flag;
            }
        }
        readiness
    }

    pub(crate) fn clear(&mut self) {
        self.revents = 0;
    }
}

/// This loops, which the function alone would not need if it kept time:
/// it counts in milliseconds and in timer ticks, and reports its timeout up
/// to one tick early. The deadline is on the unbiased interrupt time, the
/// clock `Clock::Monotonic` reads.
///
/// A timeout beyond what the function counts (an `int` of milliseconds, 24
/// days; a negative value would mean no timeout) is waited for in pieces:
/// the loop goes on until the deadline, which saturates far beyond any
/// uptime.
pub(crate) fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> Result<usize> {
    if fds.is_empty() {
        // The function refuses an empty set. The portable layer has checked
        // that there is a timeout to sleep for.
        return timeout.map_or(Ok(0), |timeout| {
            if !timeout.is_zero() {
                crate::sys::time::sleep(timeout)?;
            }
            Ok(0)
        });
    }
    let count = u32::try_from(fds.len()).unwrap_or(u32::MAX);
    let deadline = timeout.map(|timeout| unbiased().saturating_add(to_units(timeout)));
    let mut milliseconds = timeout.map_or(-1, |timeout| {
        i32::try_from(timeout.as_nanos().div_ceil(1_000_000)).unwrap_or(i32::MAX)
    });
    loop {
        // SAFETY: the function reads and writes `count` entries of the
        // slice.
        let ready = unsafe { WSAPoll(fds.as_mut_ptr(), count, milliseconds) };
        if ready == SOCKET_ERROR {
            return Err(wsa_error());
        }
        // The function does not count the entries it finds invalid, and
        // goes on waiting for the others: count, and wait no more.
        let ready = fds.iter().filter(|fd| fd.revents != 0).count();
        if ready > 0 {
            return Ok(ready);
        }
        let Some(deadline) = deadline else {
            // No timeout and nothing ready: it has nothing to say yet.
            continue;
        };
        let now = unbiased();
        if now >= deadline {
            return Ok(0);
        }
        milliseconds = i32::try_from((deadline - now).div_ceil(UNITS_PER_MS)).unwrap_or(i32::MAX);
    }
}

#[cfg(feature = "alloc")]
mod poller;
#[cfg(feature = "alloc")]
pub(crate) use poller::{Poller, RawEvent, signal_delivered, signals_dropped};