async_rs/implementors/
smol.rs1use crate::{
4 Runtime,
5 sys::AsSysFd,
6 traits::{Executor, Reactor, RuntimeKit},
7 util::{IOHandle, Task},
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
21pub type SmolRuntime = Runtime<Smol>;
23
24impl SmolRuntime {
25 pub fn smol() -> Self {
27 Self::new(Smol)
28 }
29}
30
31#[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 type Sleep = Timer;
62
63 fn register<H: Read + Write + AsSysFd + Send + 'static>(
64 &self,
65 socket: H,
66 ) -> io::Result<impl AsyncRead + AsyncWrite + Send + Unpin + 'static> {
67 Async::new(IOHandle::new(socket))
68 }
69
70 fn sleep(&self, dur: Duration) -> Self::Sleep {
71 Timer::after(dur)
72 }
73
74 fn interval(&self, dur: Duration) -> impl Stream<Item = Instant> + Send + 'static {
75 Timer::interval(dur)
76 }
77
78 fn tcp_connect_addr(
79 &self,
80 addr: SocketAddr,
81 ) -> impl Future<Output = io::Result<Self::TcpStream>> + Send + 'static {
82 Async::<TcpStream>::connect(addr)
83 }
84}
85
86mod task {
87 use crate::util::TaskImpl;
88 use async_trait::async_trait;
89 use std::{
90 future::Future,
91 pin::Pin,
92 task::{Context, Poll},
93 };
94
95 #[derive(Debug)]
97 pub struct STask<T: Send + 'static>(pub(super) Option<smol::Task<T>>);
98
99 #[async_trait]
100 impl<T: Send + 'static> TaskImpl for STask<T> {
101 async fn cancel(&mut self) -> Option<T> {
102 self.0.take()?.cancel().await
103 }
104
105 fn detach(&mut self) {
106 if let Some(task) = self.0.take() {
107 task.detach();
108 }
109 }
110 }
111
112 impl<T: Send + 'static> Future for STask<T> {
113 type Output = T;
114
115 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
116 Pin::new(self.0.as_mut().expect("task canceled")).poll(cx)
117 }
118 }
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
126 fn auto_traits() {
127 use crate::util::test::*;
128 let runtime = Runtime::smol();
129 assert_send(&runtime);
130 assert_sync(&runtime);
131 assert_clone(&runtime);
132 }
133}