dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::{
    marker,
    os::fd::{AsRawFd as _, BorrowedFd},
};

use libc::nfds_t;
use o3::base::marker::ThreadBound;

use crate::{Errno, io::poll, kernel::errno};

pub mod raw;

/// One native poll registration and the events the kernel reported for it.
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct Entry<'fd>(
    libc::pollfd,
    marker::PhantomData<(BorrowedFd<'fd>, ThreadBound)>,
);

impl<'fd> Entry<'fd> {
    /// Whether this registration count is representable by native poll.
    pub const fn is_valid_len(count: usize) -> bool {
        count as nfds_t as usize == count
    }

    /// Registers one descriptor for readability.
    pub fn readable(fd: BorrowedFd<'fd>) -> Self {
        Self::new(fd, libc::POLLIN)
    }

    /// Registers one descriptor for writability.
    pub fn writable(fd: BorrowedFd<'fd>) -> Self {
        Self::new(fd, libc::POLLOUT)
    }

    fn new(fd: BorrowedFd<'fd>, events: libc::c_short) -> Self {
        Self(
            libc::pollfd {
                fd: fd.as_raw_fd(),
                events,
                revents: 0,
            },
            marker::PhantomData,
        )
    }

    /// Whether the kernel reported any event for this registration.
    pub const fn is_ready(self) -> bool {
        self.0.revents != 0
    }

    /// Whether the kernel reported readability.
    pub const fn is_readable(self) -> bool {
        self.0.revents & libc::POLLIN != 0
    }

    /// Raw event bits reported for this registration.
    pub const fn revents(self) -> i16 {
        self.0.revents
    }

    /// Stops polling this registration after its owner handles the terminal event.
    pub fn retire(&mut self) {
        self.0.fd = -1;
        self.0.revents = 0;
    }
}

pub struct Events<'a, 'fd> {
    entries: &'a [Entry<'fd>],
    count: usize,
}

impl<'a, 'fd> Events<'a, 'fd> {
    pub const fn count(&self) -> usize {
        self.count
    }
    pub const fn entries(&self) -> &'a [Entry<'fd>] {
        self.entries
    }
}

/// Native polling against a caller-owned, bounded descriptor collection.
pub trait Poll: errno::Source {
    fn wait<'a, 'fd: 'a, T: poll::raw::Entries<'fd>, E: From<Errno>>(
        owner: &'a mut T,
        timeout: i32,
    ) -> Result<poll::Events<'a, 'fd>, E> {
        let entries = owner.entries();
        let count = raw::wait::<Self, E>(entries, timeout)?;
        Ok(poll::Events { entries, count })
    }
}

impl<T: errno::Source> Poll for T {}