actm/executor/
asyncstd.rs

1//! Support for `async_std`
2
3use std::{convert::Infallible, future::Future};
4
5use async_std::task::JoinHandle;
6use async_trait::async_trait;
7
8use super::{AsyncJoin, Executor, SyncJoin};
9use crate::types::Either;
10
11#[async_trait]
12impl<T> AsyncJoin for JoinHandle<T>
13where
14    T: Send,
15{
16    type Item = T;
17    type Error = Infallible;
18    async fn async_join(self) -> Result<Self::Item, Self::Error> {
19        Ok(self.await)
20    }
21}
22
23impl<T> SyncJoin for JoinHandle<T>
24where
25    T: Send + 'static,
26{
27    type Item = T;
28
29    type Error = Infallible;
30
31    fn sync_join(self) -> Result<Self::Item, Self::Error> {
32        Ok(futures::executor::block_on(self))
33    }
34
35    fn to_async(self) -> Either<Box<dyn AsyncJoin<Item = Self::Item, Error = Self::Error>>, Self>
36    where
37        Self: Sized,
38    {
39        Either::Happy(Box::new(self))
40    }
41}
42
43/// [`Executor`] implementation for `async_std`
44///
45/// Implements async task spawning through [`async_std::task::spawn`], and synchronous spawning
46/// through [`async_std::task::spawn_blocking`]
47pub struct AsyncStd;
48
49impl Executor for AsyncStd {
50    type AsyncJoin<T: Send + 'static> = JoinHandle<T>;
51    type SyncJoin<T: Send + 'static> = JoinHandle<T>;
52    fn spawn_async<T, F>(future: F) -> Self::AsyncJoin<T>
53    where
54        T: Send + Sync + 'static,
55        F: Future<Output = T> + Send + 'static,
56    {
57        async_std::task::spawn(future)
58    }
59
60    fn spawn_sync<T, C>(closure: C) -> Self::SyncJoin<T>
61    where
62        T: Send + Sync + 'static,
63        C: FnOnce() -> T + Send + 'static,
64    {
65        async_std::task::spawn_blocking(closure)
66    }
67}