async_global_executor_trait/
lib.rs1use async_trait::async_trait;
2use executor_trait::{Executor, 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 AsyncGlobalExecutor;
12
13struct AGETask(Option<async_global_executor::Task<()>>);
14
15#[async_trait]
16impl Executor for AsyncGlobalExecutor {
17 fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
18 async_global_executor::block_on(f);
19 }
20
21 fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Box<dyn Task> {
22 Box::new(AGETask(Some(async_global_executor::spawn(f))))
23 }
24
25 fn spawn_local(
26 &self,
27 f: Pin<Box<dyn Future<Output = ()>>>,
28 ) -> Result<Box<dyn Task>, LocalExecutorError> {
29 Ok(Box::new(AGETask(Some(async_global_executor::spawn_local(
30 f,
31 )))))
32 }
33
34 async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
35 async_global_executor::spawn_blocking(f).await;
36 }
37}
38
39#[async_trait(?Send)]
40impl Task for AGETask {
41 async fn cancel(mut self: Box<Self>) -> Option<()> {
42 self.0.take()?.cancel().await
43 }
44}
45
46impl Drop for AGETask {
47 fn drop(&mut self) {
48 if let Some(task) = self.0.take() {
49 task.detach();
50 }
51 }
52}
53
54impl Future for AGETask {
55 type Output = ();
56
57 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
58 self.0
59 .as_mut()
60 .map_or(Poll::Ready(()), |handle| Pin::new(handle).poll(cx))
61 }
62}