Skip to main content

externally_driven_async_rt/selector/
mod.rs

1mod direction;
2#[cfg(miri)]
3mod dummy;
4#[cfg(all(target_os = "linux", not(miri)))]
5mod epoll;
6mod io_change;
7mod kernel_timer;
8#[cfg(all(target_os = "macos", not(miri)))]
9mod kqueue;
10mod selector_event;
11mod timer_change;
12
13#[cfg(not(any(target_os = "macos", target_os = "linux")))]
14compile_error!("externally-driven-async-rt supports only macOS and Linux");
15
16use rustix::fd::{AsFd, BorrowedFd};
17
18#[cfg(miri)]
19use self::dummy::DummySelector as Backend;
20#[cfg(all(target_os = "linux", not(miri)))]
21use self::epoll::EpollSelector as Backend;
22#[cfg(all(target_os = "macos", not(miri)))]
23use self::kqueue::KqueueSelector as Backend;
24pub(crate) use self::{
25    direction::{Direction, Directions},
26    io_change::IoChange,
27    kernel_timer::KernelTimer,
28    selector_event::{EVENTS_PER_CALL, SelectorEvent},
29    timer_change::TimerChange,
30};
31use crate::time::Instant;
32
33/// A selector for your current platform (epoll on Linux and kqueue on macOS).
34#[must_use]
35pub struct Selector {
36    backend: Backend,
37}
38
39impl Selector {
40    /// Constructor.
41    ///
42    /// # Errors
43    ///
44    /// Returns an error if an epoll/kqueue syscall fails.
45    pub fn new() -> rustix::io::Result<Self> {
46        Ok(Self {
47            backend: Backend::new()?,
48        })
49    }
50
51    pub(crate) fn apply_now(&self, change: IoChange) -> rustix::io::Result<()> {
52        self.backend.apply_now(change)
53    }
54
55    pub(crate) fn arm_timer(&self, deadline: Instant) {
56        self.backend.arm_timer(deadline);
57    }
58
59    pub(crate) fn disarm_timer(&self) {
60        self.backend.disarm_timer();
61    }
62
63    pub(crate) fn notify(&self) -> rustix::io::Result<()> {
64        self.backend.notify()
65    }
66
67    pub(crate) fn flush(
68        &self,
69        io_changes: impl IntoIterator<Item = IoChange>,
70    ) -> rustix::io::Result<()> {
71        self.backend.flush(io_changes)
72    }
73
74    pub(crate) fn poll_nonblocking(
75        &self,
76        out: &mut [Option<SelectorEvent>; EVENTS_PER_CALL],
77    ) -> rustix::io::Result<bool> {
78        self.backend.poll_nonblocking(out)
79    }
80
81    pub(crate) fn as_fd(&self) -> BorrowedFd<'_> {
82        self.backend.as_fd()
83    }
84}
85
86impl core::fmt::Debug for Selector {
87    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
88        f.write_str("Selector")
89    }
90}
91
92#[cfg(test)]
93mod tests;