Skip to main content

whatsapp_rust/
runtime_impl.rs

1/// Tokio-based implementation of [`Runtime`]. Only available on native targets.
2#[cfg(not(target_arch = "wasm32"))]
3mod tokio_impl {
4    use std::future::Future;
5    use std::pin::Pin;
6    use std::time::Duration;
7
8    use async_trait::async_trait;
9    use wacore::runtime::{AbortHandle, Runtime};
10
11    pub struct TokioRuntime;
12
13    #[async_trait]
14    impl Runtime for TokioRuntime {
15        fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) -> AbortHandle {
16            let handle = tokio::spawn(future);
17            AbortHandle::new(move || handle.abort())
18        }
19
20        fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>> {
21            Box::pin(tokio::time::sleep(duration))
22        }
23
24        fn spawn_blocking(
25            &self,
26            f: Box<dyn FnOnce() + Send + 'static>,
27        ) -> Pin<Box<dyn Future<Output = ()> + Send>> {
28            Box::pin(async {
29                let _ = tokio::task::spawn_blocking(f).await;
30            })
31        }
32
33        fn yield_now(&self) -> Option<Pin<Box<dyn Future<Output = ()> + Send>>> {
34            // Multi-threaded runtime: other tasks run on separate threads,
35            // no cooperative yielding needed.
36            None
37        }
38    }
39}
40
41#[cfg(not(target_arch = "wasm32"))]
42pub use tokio_impl::TokioRuntime;