bastion_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 bastion
10#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
11pub struct Bastion;
12
13struct BTask(lightproc::recoverable_handle::RecoverableHandle<()>);
14
15impl FullExecutor for Bastion {}
16
17impl Executor for Bastion {
18    fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
19        bastion::run!(f);
20    }
21
22    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Box<dyn Task> {
23        Box::new(BTask(bastion::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        Err(LocalExecutorError(f))
31    }
32}
33
34#[async_trait]
35impl BlockingExecutor for Bastion {
36    async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
37        bastion::executor::blocking(async move { f() }).await;
38    }
39}
40
41#[async_trait(?Send)]
42impl Task for BTask {
43    async fn cancel(self: Box<Self>) -> Option<()> {
44        self.0.cancel();
45        self.0.await
46    }
47}
48
49impl Future for BTask {
50    type Output = ();
51
52    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
53        match Pin::new(&mut self.0).poll(cx) {
54            Poll::Pending => Poll::Pending,
55            Poll::Ready(res) => {
56                res.expect("task has been canceled");
57                Poll::Ready(())
58            }
59        }
60    }
61}