async_executor_trait/
lib.rs

1use async_trait::async_trait;
2use executor_trait::{BlockingExecutor, Executor, FullExecutor, LocalExecutorError, Task};
3use std::{
4    future::Future,
5    pin::Pin,
6    task::{Context, Poll},
7};
8
9/// Dummy object implementing executor-trait common interfaces on top of async-std
10#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
11pub struct AsyncStd;
12
13struct ASTask(async_std::task::JoinHandle<()>);
14
15impl FullExecutor for AsyncStd {}
16
17impl Executor for AsyncStd {
18    fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
19        async_std::task::block_on(f);
20    }
21
22    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Box<dyn Task> {
23        Box::new(ASTask(async_std::task::spawn(f)))
24    }
25
26    fn spawn_local(
27        &self,
28        f: Pin<Box<dyn Future<Output = ()>>>,
29    ) -> Result<Box<dyn Task>, LocalExecutorError> {
30        Ok(Box::new(ASTask(async_std::task::spawn_local(f))))
31    }
32}
33
34#[async_trait]
35impl BlockingExecutor for AsyncStd {
36    async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
37        async_std::task::spawn_blocking(f).await;
38    }
39}
40
41#[async_trait(?Send)]
42impl Task for ASTask {
43    async fn cancel(self: Box<Self>) -> Option<()> {
44        self.0.cancel().await
45    }
46}
47
48impl Future for ASTask {
49    type Output = ();
50
51    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
52        Pin::new(&mut self.0).poll(cx)
53    }
54}