petitcarnets 0.0.10

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
//! `wait_readable` with `select(2)`, for macOS, whose `poll` does not
//! support terminal devices such as `/dev/tty`.

use super::interrupted_or;
use std::ffi::c_int;
use std::io;
use std::time::Instant;

/// Descriptors an `fd_set` holds: `FD_SETSIZE`, 1024 on macOS.
const FD_SETSIZE: usize = 1024;

/// macOS's `fd_set`: `FD_SETSIZE` bits in 32-bit words.
#[repr(C)]
struct FdSet([u32; FD_SETSIZE / 32]);

/// macOS's `struct timeval`: a 64-bit `time_t` and a 32-bit
/// `suseconds_t` (padded to 16 bytes, as in C).
#[repr(C)]
struct Timeval {
    seconds: i64,
    micros: i32,
}

unsafe extern "C" {
    fn select(
        nfds: c_int,
        read: *mut FdSet,
        write: *mut FdSet,
        error: *mut FdSet,
        timeout: *mut Timeval,
    ) -> c_int;
}

/// Which of `fds` can be read without blocking (or have hung up), waiting
/// until at least one can or `deadline` passes; `None` waits as long as
/// it takes. Interrupted waits are retried with the time left.
pub(super) fn wait_readable<const N: usize>(
    fds: [c_int; N],
    deadline: Option<Instant>,
) -> io::Result<[bool; N]> {
    let slots = fds.map(slot);
    if slots.iter().any(Option::is_none) {
        return Err(io::Error::other("select cannot watch this descriptor"));
    }
    let highest = fds.iter().copied().max().unwrap_or(-1);
    loop {
        let mut set = FdSet([0; FD_SETSIZE / 32]);
        for (word, bit) in slots.iter().flatten() {
            set.0[*word] |= bit;
        }
        let mut wait = deadline.map(time_left);
        let timeout = wait
            .as_mut()
            .map_or(std::ptr::null_mut(), std::ptr::from_mut);
        let null = std::ptr::null_mut();
        // SAFETY: `set` and `wait` are live locals of the layouts macOS
        // declares; `select` only reads and rewrites them.
        let rc = unsafe { select(highest + 1, &raw mut set, null, null, timeout) };
        if rc >= 0 {
            return Ok(slots.map(|s| s.is_some_and(|(word, bit)| set.0[word] & bit != 0)));
        }
        interrupted_or(io::Error::last_os_error())?;
    }
}

/// Where `fd`'s bit is in an `fd_set`: its word and mask; `None` for a
/// descriptor an `fd_set` cannot hold.
fn slot(fd: c_int) -> Option<(usize, u32)> {
    let fd = usize::try_from(fd).ok().filter(|&fd| fd < FD_SETSIZE)?;
    Some((fd / 32, 1 << (fd % 32)))
}

/// The time until `deadline`, rounded up to the microsecond so the wait
/// never ends early.
fn time_left(deadline: Instant) -> Timeval {
    let left = deadline.saturating_duration_since(Instant::now());
    let up = left + std::time::Duration::from_nanos(999);
    Timeval {
        seconds: i64::try_from(up.as_secs()).unwrap_or(i64::MAX),
        micros: i32::try_from(up.subsec_micros()).unwrap_or(0),
    }
}