async_executor_trait/
lib.rs1use 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#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
11pub struct AsyncStd;
12
13struct ASTask(Option<async_global_executor::Task<()>>);
14
15impl FullExecutor for AsyncStd {}
16
17impl Executor for AsyncStd {
18 fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
19 async_global_executor::block_on(f);
20 }
21
22 fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Box<dyn Task> {
23 Box::new(ASTask(Some(async_global_executor::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(Some(async_global_executor::spawn_local(
31 f,
32 )))))
33 }
34}
35
36#[async_trait]
37impl BlockingExecutor for AsyncStd {
38 async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
39 async_global_executor::spawn_blocking(f).await;
40 }
41}
42
43impl Drop for ASTask {
44 fn drop(&mut self) {
45 if let Some(handle) = self.0.take() {
46 handle.detach();
47 }
48 }
49}
50
51#[async_trait(?Send)]
52impl Task for ASTask {
53 async fn cancel(mut self: Box<Self>) -> Option<()> {
54 self.0.take()?.cancel().await
55 }
56}
57
58impl Future for ASTask {
59 type Output = ();
60
61 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
62 if let Some(mut handle) = self.0.as_mut() {
63 Pin::new(&mut handle).poll(cx)
64 } else {
65 Poll::Ready(())
66 }
67 }
68}