1
- use js_sys:: { Function , Object , Reflect , Uint8Array , WebAssembly } ;
1
+ use js_sys:: { Function , Object , Reflect , WebAssembly } ;
2
2
use wasm_bindgen:: prelude:: * ;
3
3
use wasm_bindgen:: JsCast ;
4
+ use wasm_bindgen_futures:: { spawn_local, JsFuture } ;
4
5
5
6
// lifted from the `console_log` example
6
7
#[ wasm_bindgen]
@@ -15,24 +16,12 @@ macro_rules! console_log {
15
16
16
17
const WASM : & [ u8 ] = include_bytes ! ( "add.wasm" ) ;
17
18
18
- #[ wasm_bindgen( start) ]
19
- pub fn run ( ) -> Result < ( ) , JsValue > {
19
+ async fn run_async ( ) -> Result < ( ) , JsValue > {
20
20
console_log ! ( "instantiating a new wasm module directly" ) ;
21
21
22
- // Note that `Uint8Array::view` is somewhat dangerous (hence the
23
- // `unsafe`!). This is creating a raw view into our module's
24
- // `WebAssembly.Memory` buffer, but if we allocate more pages for ourself
25
- // (aka do a memory allocation in Rust) it'll cause the buffer to change,
26
- // causing the `Uint8Array` to be invalid.
27
- //
28
- // As a result, after `Uint8Array::view` we have to be very careful not to
29
- // do any memory allocations before it's dropped.
30
- let a = unsafe {
31
- let array = Uint8Array :: view ( WASM ) ;
32
- WebAssembly :: Module :: new ( array. as_ref ( ) ) ?
33
- } ;
34
-
35
- let b = WebAssembly :: Instance :: new ( & a, & Object :: new ( ) ) ?;
22
+ let a = JsFuture :: from ( WebAssembly :: instantiate_buffer ( WASM , & Object :: new ( ) ) ) . await ?;
23
+ let b: WebAssembly :: Instance = Reflect :: get ( & a, & "instance" . into ( ) ) ?. dyn_into ( ) ?;
24
+
36
25
let c = b. exports ( ) ;
37
26
38
27
let add = Reflect :: get ( c. as_ref ( ) , & "add" . into ( ) ) ?
@@ -51,3 +40,10 @@ pub fn run() -> Result<(), JsValue> {
51
40
52
41
Ok ( ( ) )
53
42
}
43
+
44
+ #[ wasm_bindgen( start) ]
45
+ pub fn run ( ) {
46
+ spawn_local ( async {
47
+ run_async ( ) . await . unwrap_throw ( ) ;
48
+ } ) ;
49
+ }
0 commit comments