async_rs/
runtime.rs

1use crate::{
2    sys::AsSysFd,
3    traits::{Executor, Reactor, RuntimeKit},
4    util::{SocketAddrsResolver, Task},
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    type Task<T: Send + 'static> = <RK as Executor>::Task<T>;
50
51    fn block_on<T, F: Future<Output = T>>(&self, f: F) -> T {
52        self.kit.block_on(f)
53    }
54
55    fn spawn<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
56        &self,
57        f: F,
58    ) -> Task<Self::Task<T>> {
59        self.kit.spawn(f)
60    }
61
62    fn spawn_blocking<T: Send + 'static, F: FnOnce() -> T + Send + 'static>(
63        &self,
64        f: F,
65    ) -> Task<Self::Task<T>> {
66        self.kit.spawn_blocking(f)
67    }
68}
69
70impl<RK: RuntimeKit> Reactor for Runtime<RK> {
71    type TcpStream = <RK as Reactor>::TcpStream;
72
73    fn register<H: Read + Write + AsSysFd + Send + 'static>(
74        &self,
75        socket: H,
76    ) -> io::Result<impl AsyncRead + AsyncWrite + Send + Unpin + 'static> {
77        self.kit.register(socket)
78    }
79
80    fn sleep(&self, dur: Duration) -> impl Future<Output = ()> + Send + 'static {
81        self.kit.sleep(dur)
82    }
83
84    fn interval(&self, dur: Duration) -> impl Stream<Item = Instant> + Send + 'static {
85        self.kit.interval(dur)
86    }
87
88    fn tcp_connect_addr(
89        &self,
90        addr: SocketAddr,
91    ) -> impl Future<Output = io::Result<Self::TcpStream>> + Send + 'static {
92        self.kit.tcp_connect_addr(addr)
93    }
94}