async_rs/implementors/
smol.rs

1//! smol implementation of async runtime definition traits
2
3use crate::{
4    Runtime,
5    sys::AsSysFd,
6    traits::{Executor, Reactor, RuntimeKit},
7    util::{IOHandle, Task, UnitFuture},
8};
9use futures_core::Stream;
10use futures_io::{AsyncRead, AsyncWrite};
11use smol::{Async, Timer};
12use std::{
13    future::Future,
14    io::{self, Read, Write},
15    net::{SocketAddr, TcpStream},
16    time::{Duration, Instant},
17};
18
19use task::STask;
20
21/// Type alias for the smol runtime
22pub type SmolRuntime = Runtime<Smol>;
23
24impl SmolRuntime {
25    /// Create a new SmolRuntime
26    pub fn smol() -> Self {
27        Self::new(Smol)
28    }
29}
30
31/// Dummy object implementing async common interfaces on top of smol
32#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
33pub struct Smol;
34
35impl RuntimeKit for Smol {}
36
37impl Executor for Smol {
38    type Task<T: Send + 'static> = STask<T>;
39
40    fn block_on<T, F: Future<Output = T>>(&self, f: F) -> T {
41        smol::block_on(f)
42    }
43
44    fn spawn<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
45        &self,
46        f: F,
47    ) -> Task<Self::Task<T>> {
48        STask(Some(smol::spawn(f))).into()
49    }
50
51    fn spawn_blocking<T: Send + 'static, F: FnOnce() -> T + Send + 'static>(
52        &self,
53        f: F,
54    ) -> Task<Self::Task<T>> {
55        STask(Some(smol::unblock(f))).into()
56    }
57}
58
59impl Reactor for Smol {
60    type TcpStream = Async<TcpStream>;
61
62    fn register<H: Read + Write + AsSysFd + Send + 'static>(
63        &self,
64        socket: H,
65    ) -> io::Result<impl AsyncRead + AsyncWrite + Send + Unpin + 'static> {
66        Async::new(IOHandle::new(socket))
67    }
68
69    fn sleep(&self, dur: Duration) -> impl Future<Output = ()> + Send + 'static {
70        UnitFuture(Timer::after(dur))
71    }
72
73    fn interval(&self, dur: Duration) -> impl Stream<Item = Instant> + Send + 'static {
74        Timer::interval(dur)
75    }
76
77    fn tcp_connect_addr(
78        &self,
79        addr: SocketAddr,
80    ) -> impl Future<Output = io::Result<Self::TcpStream>> + Send + 'static {
81        Async::<TcpStream>::connect(addr)
82    }
83}
84
85mod task {
86    use crate::util::TaskImpl;
87    use async_trait::async_trait;
88    use std::{
89        future::Future,
90        pin::Pin,
91        task::{Context, Poll},
92    };
93
94    /// A smol task
95    #[derive(Debug)]
96    pub struct STask<T: Send + 'static>(pub(super) Option<smol::Task<T>>);
97
98    #[async_trait]
99    impl<T: Send + 'static> TaskImpl for STask<T> {
100        async fn cancel(&mut self) -> Option<T> {
101            self.0.take()?.cancel().await
102        }
103
104        fn detach(&mut self) {
105            if let Some(task) = self.0.take() {
106                task.detach();
107            }
108        }
109    }
110
111    impl<T: Send + 'static> Future for STask<T> {
112        type Output = T;
113
114        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
115            Pin::new(self.0.as_mut().expect("task canceled")).poll(cx)
116        }
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn auto_traits() {
126        use crate::util::test::*;
127        let runtime = Runtime::smol();
128        assert_send(&runtime);
129        assert_sync(&runtime);
130        assert_clone(&runtime);
131    }
132}