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;
const UNITS_PER_MS: u64 = 10_000;
#[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;
});
fn wsa_error() -> Error {
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;
}
}
pub(crate) fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> Result<usize> {
if fds.is_empty() {
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 {
let ready = unsafe { WSAPoll(fds.as_mut_ptr(), count, milliseconds) };
if ready == SOCKET_ERROR {
return Err(wsa_error());
}
let ready = fds.iter().filter(|fd| fd.revents != 0).count();
if ready > 0 {
return Ok(ready);
}
let Some(deadline) = deadline else {
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};