smol_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 smol
10#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
11pub struct Smol;
12
13struct STask(Option<smol::Task<()>>);
14
15impl FullExecutor for Smol {}
16
17impl Executor for Smol {
18    fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
19        smol::block_on(f);
20    }
21
22    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Box<dyn Task> {
23        Box::new(STask(Some(smol::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 Smol {
36    async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
37        smol::unblock(f).await;
38    }
39}
40
41#[async_trait(?Send)]
42impl Task for STask {
43    async fn cancel(mut self: Box<Self>) -> Option<()> {
44        self.0.take()?.cancel().await
45    }
46}
47
48impl Drop for STask {
49    fn drop(&mut self) {
50        if let Some(task) = self.0.take() {
51            task.detach();
52        }
53    }
54}
55
56impl Future for STask {
57    type Output = ();
58
59    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
60        Pin::new(self.0.as_mut().unwrap()).poll(cx)
61    }
62}