par_stream/rt/
runtime.rs

1use crate::common::*;
2use std::any::Any;
3
4static GLOBAL_RUNTIME: OnceCell<Box<dyn Runtime>> = OnceCell::new();
5
6pub(crate) type BoxAny<'a> = Box<dyn 'a + Send + Any>;
7
8pub unsafe trait Runtime
9where
10    Self: 'static + Sync + Send,
11{
12    fn block_on<'a>(&self, fut: BoxFuture<'a, BoxAny<'static>>) -> BoxAny<'static>;
13
14    fn block_on_executor<'a>(&self, fut: BoxFuture<'a, BoxAny<'static>>) -> BoxAny<'static>;
15
16    fn spawn(&self, fut: BoxFuture<'static, BoxAny<'static>>) -> Box<dyn SpawnHandle>;
17
18    fn spawn_blocking(
19        &self,
20        f: Box<dyn FnOnce() -> BoxAny<'static> + Send>,
21    ) -> Box<dyn SpawnHandle>;
22
23    fn sleep(&self, dur: Duration) -> Box<dyn SleepHandle>;
24}
25
26pub unsafe trait SpawnHandle
27where
28    Self: Send + Future<Output = BoxAny<'static>> + Unpin,
29{
30}
31
32pub unsafe trait SleepHandle
33where
34    Self: Send + Future<Output = ()> + Unpin,
35{
36}
37
38#[allow(dead_code)]
39pub(crate) fn get_global_runtime() -> &'static Box<dyn Runtime> {
40    GLOBAL_RUNTIME
41        .get()
42        .expect("global runtime is not set, did you call set_global_runtime()?")
43}
44
45/// Sets the global runtime from a [Runtime] object.
46///
47/// It is effective only when none of `runtime-*` feature is enabled.
48pub fn set_global_runtime<R>(runtime: R) -> Result<(), &'static str>
49where
50    R: Runtime,
51{
52    GLOBAL_RUNTIME
53        .set(Box::new(runtime))
54        .map_err(|_| "set_global_runtime() cannot be called more than once")
55}