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}
63
64impl executor_trait_2::FullExecutor for AsyncGlobalExecutor {}
65
66impl executor_trait_2::Executor for AsyncGlobalExecutor {
67 fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
68 async_global_executor_trait_2::AsyncGlobalExecutor.block_on(f)
69 }
70
71 fn spawn(
72 &self,
73 f: Pin<Box<dyn Future<Output = ()> + Send>>,
74 ) -> Box<dyn executor_trait_2::Task> {
75 async_global_executor_trait_2::AsyncGlobalExecutor.spawn(f)
76 }
77
78 fn spawn_local(
79 &self,
80 f: Pin<Box<dyn Future<Output = ()>>>,
81 ) -> Result<Box<dyn executor_trait_2::Task>, executor_trait_2::LocalExecutorError> {
82 async_global_executor_trait_2::AsyncGlobalExecutor.spawn_local(f)
83 }
84}
85
86#[async_trait]
87impl executor_trait_2::BlockingExecutor for AsyncGlobalExecutor {
88 async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
89 async_global_executor_trait_2::AsyncGlobalExecutor.spawn_blocking(f).await
90 }
91}