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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use
{
	crate                :: { SpawnHandle, LocalSpawnHandle, JoinHandle, YieldNow      } ,
	wasm_bindgen_futures :: { spawn_local                                              } ,
	futures_task         :: { FutureObj, LocalFutureObj, Spawn, LocalSpawn, SpawnError } ,
	futures_util         :: { FutureExt                                                } ,
};


/// A type that implements [`Spawn`], [`LocalSpawn`], [`SpawnHandle`](crate::SpawnHandle) and [`LocalSpawnHandle`](crate::LocalSpawnHandle).
/// Spawns on the _wasm-bingen-futures_ executor. The executor is global, eg. not self contained
/// and zero sized.
//
#[ derive( Copy, Clone, Default ) ]
//
#[ cfg_attr( nightly, doc(cfg(all( feature = "bindgen", target_arch = "wasm32" ))) ) ]
//
pub struct Bindgen;


impl Bindgen
{
	/// Create a new Bindgen wrapper.
	///
	pub fn new() -> Self
	{
		Self
	}
}



impl Spawn for Bindgen
{
	fn spawn_obj( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError>
	{
		spawn_local( future );

		Ok(())
	}
}



impl LocalSpawn for Bindgen
{
	fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnError>
	{
		spawn_local( future );

		Ok(())
	}
}



impl<Out: 'static + Send> SpawnHandle<Out> for Bindgen
{
	fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
	{
		let (fut, handle) = future.remote_handle();
		spawn_local(fut);

		Ok( JoinHandle::remote_handle(handle) )
	}
}



impl<Out: 'static> LocalSpawnHandle<Out> for Bindgen
{
	fn spawn_handle_local_obj( &self, future: LocalFutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
	{
		let (fut, handle) = future.remote_handle();
		spawn_local(fut);

		Ok( JoinHandle::remote_handle(handle) )
	}
}



impl YieldNow for Bindgen {}



impl std::fmt::Debug for Bindgen
{
	fn fmt( &self, f: &mut std::fmt::Formatter<'_> ) -> std::fmt::Result
	{
		write!( f, "WASM Bindgen executor" )
	}
}



#[ cfg( feature = "timer" ) ]
//
#[ cfg_attr( nightly, doc(cfg(all( feature = "timer", feature = "bindgen" ))) ) ]
//
impl crate::Timer for Bindgen
{
	fn sleep( &self, dur: std::time::Duration ) -> futures_core::future::BoxFuture<'static, ()>
	{
		futures_timer::Delay::new( dur ).boxed()
	}
}