Skip to main content

dope_sys/io/poll/
mod.rs

1use std::{
2    marker,
3    os::fd::{AsRawFd as _, BorrowedFd},
4};
5
6use libc::nfds_t;
7use o3::base::marker::ThreadBound;
8
9use crate::{Errno, io::poll, kernel::errno};
10
11pub mod raw;
12
13/// One native poll registration and the events the kernel reported for it.
14#[derive(Clone, Copy, Debug)]
15#[repr(transparent)]
16pub struct Entry<'fd>(
17    libc::pollfd,
18    marker::PhantomData<(BorrowedFd<'fd>, ThreadBound)>,
19);
20
21impl<'fd> Entry<'fd> {
22    /// Whether this registration count is representable by native poll.
23    pub const fn is_valid_len(count: usize) -> bool {
24        count as nfds_t as usize == count
25    }
26
27    /// Registers one descriptor for readability.
28    pub fn readable(fd: BorrowedFd<'fd>) -> Self {
29        Self::new(fd, libc::POLLIN)
30    }
31
32    /// Registers one descriptor for writability.
33    pub fn writable(fd: BorrowedFd<'fd>) -> Self {
34        Self::new(fd, libc::POLLOUT)
35    }
36
37    fn new(fd: BorrowedFd<'fd>, events: libc::c_short) -> Self {
38        Self(
39            libc::pollfd {
40                fd: fd.as_raw_fd(),
41                events,
42                revents: 0,
43            },
44            marker::PhantomData,
45        )
46    }
47
48    /// Whether the kernel reported any event for this registration.
49    pub const fn is_ready(self) -> bool {
50        self.0.revents != 0
51    }
52
53    /// Whether the kernel reported readability.
54    pub const fn is_readable(self) -> bool {
55        self.0.revents & libc::POLLIN != 0
56    }
57
58    /// Raw event bits reported for this registration.
59    pub const fn revents(self) -> i16 {
60        self.0.revents
61    }
62
63    /// Stops polling this registration after its owner handles the terminal event.
64    pub fn retire(&mut self) {
65        self.0.fd = -1;
66        self.0.revents = 0;
67    }
68}
69
70pub struct Events<'a, 'fd> {
71    entries: &'a [Entry<'fd>],
72    count: usize,
73}
74
75impl<'a, 'fd> Events<'a, 'fd> {
76    pub const fn count(&self) -> usize {
77        self.count
78    }
79    pub const fn entries(&self) -> &'a [Entry<'fd>] {
80        self.entries
81    }
82}
83
84/// Native polling against a caller-owned, bounded descriptor collection.
85pub trait Poll: errno::Source {
86    fn wait<'a, 'fd: 'a, T: poll::raw::Entries<'fd>, E: From<Errno>>(
87        owner: &'a mut T,
88        timeout: i32,
89    ) -> Result<poll::Events<'a, 'fd>, E> {
90        let entries = owner.entries();
91        let count = raw::wait::<Self, E>(entries, timeout)?;
92        Ok(poll::Events { entries, count })
93    }
94}
95
96impl<T: errno::Source> Poll for T {}