1 use crate::fd::{AsFd, BorrowedFd}; 2 use bitflags::bitflags; 3 4 bitflags! { 5 /// `POLL*` flags for use with [`poll`]. 6 /// 7 /// [`poll`]: crate::io::poll 8 pub struct PollFlags: u16 { 9 /// `POLLIN` 10 const IN = linux_raw_sys::general::POLLIN as u16; 11 /// `POLLPRI` 12 const PRI = linux_raw_sys::general::POLLPRI as u16; 13 /// `POLLOUT` 14 const OUT = linux_raw_sys::general::POLLOUT as u16; 15 /// `POLLRDNORM` 16 const RDNORM = linux_raw_sys::general::POLLRDNORM as u16; 17 /// `POLLWRNORM` 18 const WRNORM = linux_raw_sys::general::POLLWRNORM as u16; 19 /// `POLLRDBAND` 20 const RDBAND = linux_raw_sys::general::POLLRDBAND as u16; 21 /// `POLLWRBAND` 22 const WRBAND = linux_raw_sys::general::POLLWRBAND as u16; 23 /// `POLLERR` 24 const ERR = linux_raw_sys::general::POLLERR as u16; 25 /// `POLLHUP` 26 const HUP = linux_raw_sys::general::POLLHUP as u16; 27 /// `POLLNVAL` 28 const NVAL = linux_raw_sys::general::POLLNVAL as u16; 29 /// `POLLRDHUP` 30 const RDHUP = linux_raw_sys::general::POLLRDHUP as u16; 31 } 32 } 33 34 /// `struct pollfd`—File descriptor and flags for use with [`poll`]. 35 /// 36 /// [`poll`]: crate::io::poll 37 #[doc(alias = "pollfd")] 38 #[repr(C)] 39 #[derive(Debug, Clone)] 40 pub struct PollFd<'fd> { 41 pub(crate) fd: BorrowedFd<'fd>, 42 pub(crate) events: u16, 43 pub(crate) revents: u16, 44 } 45 46 impl<'fd> PollFd<'fd> { 47 /// Constructs a new `PollFd` holding `fd` and `events`. 48 #[inline] new<Fd: AsFd>(fd: &'fd Fd, events: PollFlags) -> Self49 pub fn new<Fd: AsFd>(fd: &'fd Fd, events: PollFlags) -> Self { 50 Self::from_borrowed_fd(fd.as_fd(), events) 51 } 52 53 /// Sets the contained file descriptor to `fd`. 54 #[inline] set_fd<Fd: AsFd>(&mut self, fd: &'fd Fd)55 pub fn set_fd<Fd: AsFd>(&mut self, fd: &'fd Fd) { 56 self.fd = fd.as_fd(); 57 } 58 59 /// Clears the ready events. 60 #[inline] clear_revents(&mut self)61 pub fn clear_revents(&mut self) { 62 self.revents = 0; 63 } 64 65 /// Constructs a new `PollFd` holding `fd` and `events`. 66 /// 67 /// This is the same as `new`, but can be used to avoid borrowing the 68 /// `BorrowedFd`, which can be tricky in situations where the `BorrowedFd` 69 /// is a temporary. 70 #[inline] from_borrowed_fd(fd: BorrowedFd<'fd>, events: PollFlags) -> Self71 pub fn from_borrowed_fd(fd: BorrowedFd<'fd>, events: PollFlags) -> Self { 72 Self { 73 fd, 74 events: events.bits(), 75 revents: 0, 76 } 77 } 78 79 /// Returns the ready events. 80 #[inline] revents(&self) -> PollFlags81 pub fn revents(&self) -> PollFlags { 82 // Use `unwrap()` here because in theory we know we know all the bits 83 // the OS might set here, but OS's have added extensions in the past. 84 PollFlags::from_bits(self.revents).unwrap() 85 } 86 } 87 88 impl<'fd> AsFd for PollFd<'fd> { 89 #[inline] as_fd(&self) -> BorrowedFd<'_>90 fn as_fd(&self) -> BorrowedFd<'_> { 91 self.fd.as_fd() 92 } 93 } 94