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;
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct Entry<'fd>(
libc::pollfd,
marker::PhantomData<(BorrowedFd<'fd>, ThreadBound)>,
);
impl<'fd> Entry<'fd> {
pub const fn is_valid_len(count: usize) -> bool {
count as nfds_t as usize == count
}
pub fn readable(fd: BorrowedFd<'fd>) -> Self {
Self::new(fd, libc::POLLIN)
}
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,
)
}
pub const fn is_ready(self) -> bool {
self.0.revents != 0
}
pub const fn is_readable(self) -> bool {
self.0.revents & libc::POLLIN != 0
}
pub const fn revents(self) -> i16 {
self.0.revents
}
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
}
}
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 {}