async_io/reactor/
unix.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use polling::{Event, Poller};
4
5use std::fmt;
6use std::io::Result;
7use std::os::unix::io::{AsRawFd, BorrowedFd, RawFd};
8
9/// The raw registration into the reactor.
10#[doc(hidden)]
11pub struct Registration {
12    /// Raw file descriptor on Unix.
13    ///
14    /// # Invariant
15    ///
16    /// This describes a valid file descriptor that has not been `close`d. It will not be
17    /// closed while this object is alive.
18    raw: RawFd,
19}
20
21impl fmt::Debug for Registration {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        fmt::Debug::fmt(&self.raw, f)
24    }
25}
26
27impl Registration {
28    /// Add this file descriptor into the reactor.
29    ///
30    /// # Safety
31    ///
32    /// The provided file descriptor must be valid and not be closed while this object is alive.
33    pub(crate) unsafe fn new(f: BorrowedFd<'_>) -> Self {
34        Self { raw: f.as_raw_fd() }
35    }
36
37    /// Registers the object into the reactor.
38    #[inline]
39    pub(crate) fn add(&self, poller: &Poller, token: usize) -> Result<()> {
40        // SAFETY: This object's existence validates the invariants of Poller::add
41        unsafe { poller.add(self.raw, Event::none(token)) }
42    }
43
44    /// Re-registers the object into the reactor.
45    #[inline]
46    pub(crate) fn modify(&self, poller: &Poller, interest: Event) -> Result<()> {
47        // SAFETY: self.raw is a valid file descriptor
48        let fd = unsafe { BorrowedFd::borrow_raw(self.raw) };
49        poller.modify(fd, interest)
50    }
51
52    /// Deregisters the object from the reactor.
53    #[inline]
54    pub(crate) fn delete(&self, poller: &Poller) -> Result<()> {
55        // SAFETY: self.raw is a valid file descriptor
56        let fd = unsafe { BorrowedFd::borrow_raw(self.raw) };
57        poller.delete(fd)
58    }
59}