@@ -18,20 +18,19 @@ const WASM: &[u8] = include_bytes!("add.wasm");
18
18
#[ wasm_bindgen( start) ]
19
19
pub fn run ( ) -> Result < ( ) , JsValue > {
20
20
console_log ! ( "instantiating a new wasm module directly" ) ;
21
- let my_memory = wasm_bindgen:: memory ( )
22
- . dyn_into :: < WebAssembly :: Memory > ( )
23
- . unwrap ( ) ;
24
-
25
- // Note that this is somewhat dangerous, once we look at our
26
- // `WebAssembly.Memory` buffer then if we allocate more pages for ourself
27
- // (aka do a memory allocation in Rust) it'll cause the buffer to change.
28
- // That means we can't actually do any memory allocations after we do this
29
- // until we pass it back to JS.
30
- let my_memory = Uint8Array :: new ( & my_memory. buffer ( ) ) . subarray (
31
- WASM . as_ptr ( ) as u32 ,
32
- WASM . as_ptr ( ) as u32 + WASM . len ( ) as u32 ,
33
- ) ;
34
- let a = WebAssembly :: Module :: new ( my_memory. as_ref ( ) ) ?;
21
+
22
+ // Note that `Uint8Array::view` this 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 next used.
30
+ let a = unsafe {
31
+ let array = Uint8Array :: view ( WASM ) ;
32
+ WebAssembly :: Module :: new ( array. as_ref ( ) ) ?
33
+ } ;
35
34
let b = WebAssembly :: Instance :: new ( & a, & Object :: new ( ) ) ?;
36
35
let c = b. exports ( ) ;
37
36
0 commit comments