async_reactor_trait/
lib.rs1use 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#[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 async fn connect<A: Into<SocketAddr> + Send>(
36 addr: A,
37 ) -> io::Result<Box<dyn AsyncIOHandle + Send>> {
38 Ok(Box::new(Async::<TcpStream>::connect(addr.into()).await?))
39 }
40}