async_rs/
runtime.rs

1use crate::{
2    sys::AsSysFd,
3    traits::{Executor, Reactor, RuntimeKit, Task},
4    util::SocketAddrsResolver,
5};
6use futures_core::Stream;
7use futures_io::{AsyncRead, AsyncWrite};
8use std::{
9    future::Future,
10    io::{self, Read, Write},
11    net::{SocketAddr, ToSocketAddrs},
12    time::{Duration, Instant},
13};
14
15/// A full-featured Runtime implementation
16#[derive(Clone, Debug)]
17pub struct Runtime<RK: RuntimeKit> {
18    kit: RK,
19}
20
21impl<RK: RuntimeKit> Runtime<RK> {
22    /// Create a new Runtime from a RuntimeKit
23    pub fn new(kit: RK) -> Self {
24        Self { kit }
25    }
26
27    /// Asynchronously resolve the given domain name
28    pub fn to_socket_addrs<A: ToSocketAddrs + Send + 'static>(
29        &self,
30        addrs: A,
31    ) -> SocketAddrsResolver<'_, RK, A>
32    where
33        <A as std::net::ToSocketAddrs>::Iter: Send + 'static,
34    {
35        SocketAddrsResolver {
36            runtime: self,
37            addrs,
38        }
39    }
40}
41
42impl<RK: RuntimeKit> From<RK> for Runtime<RK> {
43    fn from(kit: RK) -> Self {
44        Self::new(kit)
45    }
46}
47
48impl<RK: RuntimeKit> Executor for Runtime<RK> {
49    fn block_on<T, F: Future<Output = T>>(&self, f: F) -> T {
50        self.kit.block_on(f)
51    }
52
53    fn spawn<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
54        &self,
55        f: F,
56    ) -> impl Task<T> + 'static {
57        self.kit.spawn(f)
58    }
59
60    fn spawn_blocking<T: Send + 'static, F: FnOnce() -> T + Send + 'static>(
61        &self,
62        f: F,
63    ) -> impl Task<T> + 'static {
64        self.kit.spawn_blocking(f)
65    }
66}
67
68impl<RK: RuntimeKit> Reactor for Runtime<RK> {
69    type TcpStream = <RK as Reactor>::TcpStream;
70
71    fn register<H: Read + Write + AsSysFd + Send + 'static>(
72        &self,
73        socket: H,
74    ) -> io::Result<impl AsyncRead + AsyncWrite + Send + Unpin + 'static> {
75        self.kit.register(socket)
76    }
77
78    fn sleep(&self, dur: Duration) -> impl Future<Output = ()> + Send + 'static {
79        self.kit.sleep(dur)
80    }
81
82    fn interval(&self, dur: Duration) -> impl Stream<Item = Instant> + Send + 'static {
83        self.kit.interval(dur)
84    }
85
86    fn tcp_connect_addr(
87        &self,
88        addr: SocketAddr,
89    ) -> impl Future<Output = io::Result<Self::TcpStream>> + Send + 'static {
90        self.kit.tcp_connect_addr(addr)
91    }
92}