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