Created
June 27, 2020 11:37
-
-
Save cloudhead/4853abf71baea8585474dda803c0cdf9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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