compio_net/poll_fd/
mod.rs

1cfg_if::cfg_if! {
2    if #[cfg(windows)] {
3        #[path = "windows.rs"]
4        mod sys;
5    } else if #[cfg(unix)] {
6        #[path = "unix.rs"]
7        mod sys;
8    }
9}
10
11#[cfg(windows)]
12use std::os::windows::io::{AsRawSocket, RawSocket};
13use std::{io, ops::Deref};
14
15use compio_buf::IntoInner;
16use compio_driver::{AsFd, AsRawFd, BorrowedFd, RawFd, SharedFd, ToSharedFd};
17
18/// A wrapper for socket, providing functionalities to wait for readiness.
19#[derive(Debug)]
20pub struct PollFd<T: AsFd>(sys::PollFd<T>);
21
22impl<T: AsFd> PollFd<T> {
23    /// Create [`PollFd`] without attaching the source. Ready-based sources need
24    /// not to be attached.
25    pub fn new(source: T) -> io::Result<Self> {
26        Self::from_shared_fd(SharedFd::new(source))
27    }
28
29    pub(crate) fn from_shared_fd(inner: SharedFd<T>) -> io::Result<Self> {
30        Ok(Self(sys::PollFd::new(inner)?))
31    }
32}
33
34impl<T: AsFd + 'static> PollFd<T> {
35    /// Wait for accept readiness, before calling `accept`, or after `accept`
36    /// returns `WouldBlock`.
37    pub async fn accept_ready(&self) -> io::Result<()> {
38        self.0.accept_ready().await
39    }
40
41    /// Wait for connect readiness.
42    pub async fn connect_ready(&self) -> io::Result<()> {
43        self.0.connect_ready().await
44    }
45
46    /// Wait for read readiness.
47    pub async fn read_ready(&self) -> io::Result<()> {
48        self.0.read_ready().await
49    }
50
51    /// Wait for write readiness.
52    pub async fn write_ready(&self) -> io::Result<()> {
53        self.0.write_ready().await
54    }
55}
56
57impl<T: AsFd> IntoInner for PollFd<T> {
58    type Inner = SharedFd<T>;
59
60    fn into_inner(self) -> Self::Inner {
61        self.0.into_inner()
62    }
63}
64
65impl<T: AsFd> ToSharedFd<T> for PollFd<T> {
66    fn to_shared_fd(&self) -> SharedFd<T> {
67        self.0.to_shared_fd()
68    }
69}
70
71impl<T: AsFd> AsFd for PollFd<T> {
72    fn as_fd(&self) -> BorrowedFd<'_> {
73        self.0.as_fd()
74    }
75}
76
77impl<T: AsFd> AsRawFd for PollFd<T> {
78    fn as_raw_fd(&self) -> RawFd {
79        self.0.as_raw_fd()
80    }
81}
82
83#[cfg(windows)]
84impl<T: AsFd + AsRawSocket> AsRawSocket for PollFd<T> {
85    fn as_raw_socket(&self) -> RawSocket {
86        self.0.as_raw_socket()
87    }
88}
89
90impl<T: AsFd> Deref for PollFd<T> {
91    type Target = T;
92
93    fn deref(&self) -> &Self::Target {
94        &self.0
95    }
96}