forked from hyperium/tonic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.rs
63 lines (54 loc) · 1.38 KB
/
executor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use crate::transport::BoxFuture;
use std::{future::Future, sync::Arc};
pub(crate) use hyper::rt::Executor;
#[cfg(not(target_arch = "wasm32"))]
#[derive(Copy, Clone)]
struct TokioExec;
#[cfg(not(target_arch = "wasm32"))]
impl<F> Executor<F> for TokioExec
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
fn execute(&self, fut: F) {
tokio::spawn(fut);
}
}
#[cfg(target_arch = "wasm32")]
#[derive(Copy, Clone)]
struct WasmBindgenExec;
#[cfg(target_arch = "wasm32")]
impl<F> Executor<F> for WasmBindgenExec
where
F: Future + 'static,
F::Output: 'static,
{
fn execute(&self, fut: F) {
wasm_bindgen_futures::spawn_local(async move {fut.await;});
}
}
#[derive(Clone)]
pub(crate) struct SharedExec {
inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
}
impl SharedExec {
pub(crate) fn new<E>(exec: E) -> Self
where
E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
{
Self {
inner: Arc::new(exec),
}
}
pub(crate) fn default_exec() -> Self {
#[cfg(not(target_arch = "wasm32"))]
return Self::new(TokioExec);
#[cfg(target_arch = "wasm32")]
Self::new(WasmBindgenExec)
}
}
impl Executor<BoxFuture<'static, ()>> for SharedExec {
fn execute(&self, fut: BoxFuture<'static, ()>) {
self.inner.execute(fut)
}
}