enfync/builtin/native/
handle_impls.rs

1//local shortcuts
2use crate::*;
3
4//third-party shortcuts
5
6//standard shortcuts
7use std::fmt::Debug;
8use std::future::Future;
9
10//-------------------------------------------------------------------------------------------------------------------
11
12/// Built-in IO runtime handle (spawns tokio tasks).
13///
14/// If you access this via `::default()`, you will get a handle to a statically-initialized tokio runtime.
15#[derive(Clone, Debug)]
16pub struct TokioHandle(pub tokio::runtime::Handle);
17
18impl Handle for TokioHandle
19{
20    fn spawn<R, F>(&self, task: F) -> PendingResult<R>
21    where
22        R: Debug + Send + Sync + 'static,
23        F: Future<Output = R> + Send + 'static
24    {
25        let spawner = builtin::native::TokioSpawner::<R>::from(self.0.clone());
26        let result_receiver = SimpleResultReceiver::new(&spawner, task);
27        PendingResult::new(result_receiver)
28    }
29}
30
31impl Default for TokioHandle
32{
33    fn default() -> TokioHandle
34    {
35        static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
36
37        let runtime = RUNTIME.get_or_init(
38                || { tokio::runtime::Runtime::new().expect("unable to make default tokio runtime") }
39            );
40        TokioHandle(runtime.handle().clone())
41    }
42}
43
44impl TryAdopt for TokioHandle
45{
46    fn try_adopt() -> Option<TokioHandle>
47    {
48        let Ok(handle) = tokio::runtime::Handle::try_current() else { return None; };
49        Some(TokioHandle::from(handle))
50    }
51}
52
53impl From<TokioHandle> for tokio::runtime::Handle
54{ fn from(handle: TokioHandle) -> Self { handle.0 } }
55
56impl From<tokio::runtime::Handle> for TokioHandle
57{ fn from(handle: tokio::runtime::Handle) -> Self { Self(handle) } }
58
59//-------------------------------------------------------------------------------------------------------------------
60
61/// Built-in CPU runtime handle (makes new std threads).
62#[derive(Clone, Default)]
63pub struct CPUHandle;
64
65impl Handle for CPUHandle
66{
67    fn spawn<R, F>(&self, task: F) -> PendingResult<R>
68    where
69        R: Debug + Send + Sync + 'static,
70        F: Future<Output = R> + Send + 'static
71    {
72        let result_receiver = OneshotResultReceiver::new(&builtin::native::StdSpawner{}, task);
73        PendingResult::new(result_receiver)
74    }
75}
76
77impl TryAdopt for CPUHandle { fn try_adopt() -> Option<CPUHandle> { Some(CPUHandle) } }
78
79//-------------------------------------------------------------------------------------------------------------------