Skip to main content

compio_compat/sys/unix/
futures.rs

1use std::{io, ops::Deref, time::Duration};
2
3use async_io::Async;
4use compio_runtime::Runtime;
5use futures_util::FutureExt;
6
7use crate::{Adapter, sys::unix::UnixAdapter};
8
9/// Adapter for general runtime. It is driven by `async-io`.
10pub struct FuturesAdapter(Async<UnixAdapter>);
11
12impl Adapter for FuturesAdapter {
13    fn new(runtime: Runtime) -> io::Result<Self> {
14        Ok(Self(Async::new_nonblocking(UnixAdapter::new(runtime)?)?))
15    }
16
17    async fn wait(&self, timeout: Option<Duration>) -> io::Result<()> {
18        let fut = self.0.readable();
19        if let Some(timeout) = timeout {
20            let timer = async_io::Timer::after(timeout);
21            futures_util::select! {
22                res = fut.fuse() => res,
23                _ = timer.fuse() => Err(io::ErrorKind::TimedOut.into()),
24            }
25        } else {
26            fut.await
27        }
28    }
29
30    fn clear(&self) -> io::Result<()> {
31        self.0.get_ref().clear()
32    }
33}
34
35impl Deref for FuturesAdapter {
36    type Target = Runtime;
37
38    fn deref(&self) -> &Self::Target {
39        self.0.get_ref()
40    }
41}