use std::os::fd::BorrowedFd;
use std::time::{Duration, Instant};
use rustix::event::{poll, PollFd, PollFlags, Timespec};
pub(crate) fn is_readable(fd: BorrowedFd<'_>) -> std::io::Result<bool> {
look_readable(fd).map_err(std::io::Error::from)
}
#[derive(Debug)]
pub(crate) enum PollFailure {
Call(rustix::io::Errno),
Revents(std::io::Error),
}
impl From<PollFailure> for std::io::Error {
fn from(failure: PollFailure) -> std::io::Error {
match failure {
PollFailure::Call(errno) => errno.into(),
PollFailure::Revents(error) => error,
}
}
}
pub(crate) fn look_readable(fd: BorrowedFd<'_>) -> Result<bool, PollFailure> {
let mut fds = [PollFd::new(&fd, PollFlags::IN)];
if !crate::wait::any_ready_now(&mut fds).map_err(PollFailure::Call)? {
return Ok(false);
}
readable(fds[0].revents()).map(|()| true).map_err(PollFailure::Revents)
}
const MAX_POLL_BLOCK: Duration = Duration::from_millis(i32::MAX as u64);
pub(crate) fn poll_readable(fd: BorrowedFd<'_>, deadline: Option<Instant>) -> std::io::Result<bool> {
let Some(deadline) = deadline else {
#[cfg(test)]
crate::wait::block_probe::blocking(None, crate::wait::block_probe::WaitObject::Fd(fd));
let mut fds = [PollFd::new(&fd, PollFlags::IN)];
crate::wait::poll_ready(&mut fds)?;
return readable(fds[0].revents()).map(|()| true);
};
let seen = crate::wait::rearm_until(Some(deadline), |remaining| {
let remaining = remaining.map(|d| d.min(MAX_POLL_BLOCK));
#[cfg(test)]
crate::wait::block_probe::blocking(remaining, crate::wait::block_probe::WaitObject::Fd(fd));
let ts = remaining.map(|d| Timespec {
tv_sec: d.as_secs() as i64,
tv_nsec: d.subsec_nanos() as _,
});
debug_assert!(ts.is_some(), "a deadline wait armed an unbounded poll");
let mut fds = [PollFd::new(&fd, PollFlags::IN)];
match poll(&mut fds, ts.as_ref()) {
Ok(0) => Ok(None),
Ok(_) => readable(fds[0].revents()).map(Some),
Err(rustix::io::Errno::INTR) => Ok(None),
Err(e) => Err(std::io::Error::from(e)),
}
})?;
Ok(seen.is_some())
}
fn readable(revents: PollFlags) -> std::io::Result<()> {
debug_assert!(
!revents.contains(PollFlags::NVAL),
"poll reported POLLNVAL: owned-fd contract violation"
);
if revents.contains(PollFlags::NVAL) {
return Err(std::io::Error::other("poll reported POLLNVAL on an owned descriptor"));
}
if revents.contains(PollFlags::ERR) {
return Err(std::io::Error::other("poll returned POLLERR"));
}
Ok(())
}
#[cfg(test)]
#[path = "poll_tests.rs"]
mod poll_tests;