|
| 1 | +cfg_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)] |
| 12 | +use std::os::windows::io::{AsRawSocket, RawSocket}; |
| 13 | +use std::{io, ops::Deref}; |
| 14 | + |
| 15 | +use compio_buf::IntoInner; |
| 16 | +use compio_driver::{AsRawFd, RawFd, SharedFd, ToSharedFd}; |
| 17 | + |
| 18 | +/// A wrapper for socket, providing functionalities to wait for readiness. |
| 19 | +#[derive(Debug)] |
| 20 | +pub struct PollFd<T: AsRawFd>(sys::PollFd<T>); |
| 21 | + |
| 22 | +impl<T: AsRawFd> 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 | + |
| 34 | +impl<T: AsRawFd + '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 | + |
| 57 | +impl<T: AsRawFd> 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 | + |
| 65 | +impl<T: AsRawFd> ToSharedFd<T> for PollFd<T> { |
| 66 | + fn to_shared_fd(&self) -> SharedFd<T> { |
| 67 | + self.0.to_shared_fd() |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl<T: AsRawFd> AsRawFd for PollFd<T> { |
| 72 | + fn as_raw_fd(&self) -> RawFd { |
| 73 | + self.0.as_raw_fd() |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +#[cfg(windows)] |
| 78 | +impl<T: AsRawFd + AsRawSocket> AsRawSocket for PollFd<T> { |
| 79 | + fn as_raw_socket(&self) -> RawSocket { |
| 80 | + self.0.as_raw_socket() |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +impl<T: AsRawFd> Deref for PollFd<T> { |
| 85 | + type Target = T; |
| 86 | + |
| 87 | + fn deref(&self) -> &Self::Target { |
| 88 | + &self.0 |
| 89 | + } |
| 90 | +} |
0 commit comments