Skip to main content

smol_executor_trait/
lib.rs

1use 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/// 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
15#[async_trait]
16impl Executor for Smol {
17    fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
18        smol::block_on(f);
19    }
20
21    fn spawn(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) -> Box<dyn Task> {
22        Box::new(STask(Some(smol::spawn(f))))
23    }
24
25    fn spawn_local(
26        &self,
27        f: Pin<Box<dyn Future<Output = ()>>>,
28    ) -> Result<Box<dyn Task>, LocalExecutorError> {
29        Err(LocalExecutorError(f))
30    }
31
32    async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
33        smol::unblock(f).await;
34    }
35}
36
37#[async_trait(?Send)]
38impl Task for STask {
39    async fn cancel(mut self: Box<Self>) -> Option<()> {
40        self.0.take()?.cancel().await
41    }
42}
43
44impl Drop for STask {
45    fn drop(&mut self) {
46        if let Some(task) = self.0.take() {
47            task.detach();
48        }
49    }
50}
51
52impl Future for STask {
53    type Output = ();
54
55    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
56        Pin::new(self.0.as_mut().unwrap()).poll(cx)
57    }
58}
59
60impl executor_trait_2::FullExecutor for Smol {}
61
62impl executor_trait_2::Executor for Smol {
63    fn block_on(&self, f: Pin<Box<dyn Future<Output = ()>>>) {
64        smol_executor_trait_3::Smol.block_on(f)
65    }
66
67    fn spawn(
68        &self,
69        f: Pin<Box<dyn Future<Output = ()> + Send>>,
70    ) -> Box<dyn executor_trait_2::Task> {
71        smol_executor_trait_3::Smol.spawn(f)
72    }
73
74    fn spawn_local(
75        &self,
76        f: Pin<Box<dyn Future<Output = ()>>>,
77    ) -> Result<Box<dyn executor_trait_2::Task>, executor_trait_2::LocalExecutorError> {
78        smol_executor_trait_3::Smol.spawn_local(f)
79    }
80}
81
82#[async_trait]
83impl executor_trait_2::BlockingExecutor for Smol {
84    async fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send + 'static>) {
85        smol_executor_trait_3::Smol.spawn_blocking(f).await
86    }
87}