Skip to content

Instantly share code, notes, and snippets.

@cloudhead
Created June 27, 2020 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudhead/4853abf71baea8585474dda803c0cdf9 to your computer and use it in GitHub Desktop.
Save cloudhead/4853abf71baea8585474dda803c0cdf9 to your computer and use it in GitHub Desktop.
use std::io;
use std::net;
use std::os::unix::io::AsRawFd;
use std::os::unix::io::RawFd;
use std::time;
#[repr(C, packed)]
pub struct Descriptor {
fd: RawFd,
events: libc::c_short,
revents: libc::c_short,
}
impl From<net::TcpStream> for Descriptor {
fn from(s: net::TcpStream) -> Self {
Self {
fd: s.as_raw_fd(),
events: 0,
revents: 0,
}
}
}
#[allow(non_camel_case_types)]
type nfds_t = libc::c_ulong;
#[derive(Debug, Copy, Clone)]
pub enum Poll {
Timeout,
Selected(usize),
}
pub fn poll(fds: &mut [Descriptor], timeout: time::Duration) -> Result<Poll, io::Error> {
let timeout = timeout.as_millis() as libc::c_int;
let result = unsafe {
libc::poll(
fds.as_mut_ptr() as *mut libc::pollfd,
fds.len() as nfds_t,
timeout,
)
};
if result == 0 {
Ok(Poll::Timeout)
} else if result > 0 {
Ok(Poll::Selected(result as usize))
} else {
Err(io::Error::last_os_error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment