async_reactor_trait/
lib.rs

1use async_io::{Async, Timer};
2use async_trait::async_trait;
3use futures_core::Stream;
4use reactor_trait::{AsyncIOHandle, IOHandle, Reactor, TcpReactor, TimeReactor};
5use std::{
6    io,
7    net::{SocketAddr, TcpStream},
8    time::{Duration, Instant},
9};
10
11/// Dummy object implementing reactor-trait common interfaces on top of async-io
12#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
13pub struct AsyncIo;
14
15impl Reactor for AsyncIo {
16    fn register(&self, socket: IOHandle) -> io::Result<Box<dyn AsyncIOHandle + Send>> {
17        Ok(Box::new(Async::new(socket)?))
18    }
19}
20
21#[async_trait]
22impl TimeReactor for AsyncIo {
23    async fn sleep(&self, dur: Duration) {
24        Timer::after(dur).await;
25    }
26
27    fn interval(&self, dur: Duration) -> Box<dyn Stream<Item = Instant>> {
28        Box::new(Timer::interval(dur))
29    }
30}
31
32#[async_trait]
33impl TcpReactor for AsyncIo {
34    /// Create a TcpStream by connecting to a remove host
35    async fn connect(&self, addr: SocketAddr) -> io::Result<Box<dyn AsyncIOHandle + Send>> {
36        Ok(Box::new(Async::<TcpStream>::connect(addr).await?))
37    }
38}