Skip to main content

compio_compat/sys/unix/
tokio.rs

1use std::{io, ops::Deref, time::Duration};
2
3use compio_runtime::Runtime;
4use tokio::io::{Interest, unix::AsyncFd};
5
6use crate::{Adapter, sys::unix::UnixAdapter};
7
8/// Adapter for `tokio` runtime.
9pub struct TokioAdapter(AsyncFd<UnixAdapter>);
10
11impl Adapter for TokioAdapter {
12    fn new(runtime: Runtime) -> io::Result<Self> {
13        Ok(Self(AsyncFd::with_interest(
14            UnixAdapter::new(runtime)?,
15            Interest::READABLE,
16        )?))
17    }
18
19    async fn wait(&self, timeout: Option<Duration>) -> io::Result<()> {
20        let fut = self.0.readable();
21        let mut guard = if let Some(timeout) = timeout {
22            tokio::time::timeout(timeout, fut).await??
23        } else {
24            fut.await?
25        };
26        guard.clear_ready();
27        Ok(())
28    }
29
30    fn clear(&self) -> io::Result<()> {
31        self.0.get_ref().clear()
32    }
33}
34
35impl Deref for TokioAdapter {
36    type Target = Runtime;
37
38    fn deref(&self) -> &Self::Target {
39        self.0.get_ref()
40    }
41}