1use libc;
6use super::error::*;
7pub use libc::pollfd;
8use ::alloc::vec;
9use ::alloc::vec::Vec;
10
11bitflags! {
12 #[repr(transparent)]
13 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14 pub struct Flags: ::libc::c_short {
15 const IN = ::libc::POLLIN;
16 const PRI = ::libc::POLLPRI;
17 const OUT = ::libc::POLLOUT;
18 const ERR = ::libc::POLLERR;
19 const HUP = ::libc::POLLHUP;
20 const NVAL = ::libc::POLLNVAL;
21 }
22}
23
24pub trait Descriptors {
25 fn count(&self) -> usize;
26 fn fill(&self, _: &mut [pollfd]) -> Result<usize>;
27 fn revents(&self, _: &[pollfd]) -> Result<Flags>;
28
29 fn get(&self) -> Result<Vec<pollfd>> {
31 let mut v = vec![pollfd { fd: 0, events: 0, revents: 0 }; self.count()];
32 if self.fill(&mut v)? != v.len() { Err(Error::unsupported("did not fill the poll descriptors array")) }
33 else { Ok(v) }
34 }
35}
36
37impl Descriptors for pollfd {
38 fn count(&self) -> usize { 1 }
39 fn fill(&self, a: &mut [pollfd]) -> Result<usize> { a[0] = *self; Ok(1) }
40 fn revents(&self, a: &[pollfd]) -> Result<Flags> { Ok(Flags::from_bits_truncate(a[0].revents)) }
41}
42
43pub fn poll(fds: &mut[pollfd], timeout: i32) -> Result<usize> {
45 let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout as libc::c_int) };
46 if r >= 0 { Ok(r as usize) } else {
47 #[cfg(feature = "std")]
48 { from_code(
49 "poll",
50 -std::io::Error::last_os_error().raw_os_error().unwrap_or_default()).map(|_| unreachable!())
51 }
52 #[cfg(not(feature = "std"))]
53 { from_code("poll", -unsafe {super::error::errno}).map(|_| unreachable!()) }
54
55 }
56}
57
58pub fn poll_all<'a>(desc: &[&'a dyn Descriptors], timeout: i32) -> Result<Vec<(&'a dyn Descriptors, Flags)>> {
60
61 let mut pollfds: Vec<pollfd> = vec!();
62 let mut indices = vec!();
63 for v2 in desc.iter().map(|q| q.get()) {
64 let v = v2?;
65 indices.push(pollfds.len() .. pollfds.len()+v.len());
66 pollfds.extend(v);
67 };
68
69 poll(&mut pollfds, timeout)?;
70
71 let mut res = vec!();
72 for (i, r) in indices.into_iter().enumerate() {
73 let z = desc[i].revents(&pollfds[r])?;
74 if !z.is_empty() { res.push((desc[i], z)); }
75 }
76 Ok(res)
77}