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
64
65
66
67
68
69
70
71
72
73
use futures::FutureExt;
pub type ErrorOf<E> = <E as Executor>::Error;
pub trait Executor: 'static {
type Error;
fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
self,
task: F,
) -> Result<(), Self::Error>;
}
impl<S: futures::task::Spawn + 'static> Executor for S {
type Error = futures::task::SpawnError;
fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
self,
task: F,
) -> Result<(), Self::Error> {
self.spawn_obj(futures::task::FutureObj::from(task.boxed()))
}
}
pub struct StdThread;
impl Default for StdThread {
fn default() -> Self {
Self
}
}
impl Executor for StdThread {
type Error = std::io::Error;
fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
self,
task: F,
) -> Result<(), Self::Error> {
let thread_buidler = std::thread::Builder::new();
thread_buidler
.spawn(|| {
futures::executor::block_on(task);
})
.map(|_| ())
}
}
#[cfg(feature = "wasm-bindgen-futures")]
pub struct WasmExecutor;
#[cfg(feature = "wasm-bindgen-futures")]
impl Executor for WasmExecutor {
type Error = ();
fn execute<F: std::future::Future<Output = ()> + Send + 'static>(
self,
task: F,
) -> Result<(), Self::Error> {
wasm_bindgen_futures::spawn_local(task);
Ok(())
}
}