Skip to content

Commit b71b136

Browse files
Pauanalexcrichton
authored andcommitted
Changing wasm-in-wasm example to be async (#1903)
1 parent 057c915 commit b71b136

File tree

2 files changed

+14
-17
lines changed

2 files changed

+14
-17
lines changed

examples/wasm-in-wasm/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ crate-type = ["cdylib"]
1010
[dependencies]
1111
wasm-bindgen = "0.2.55"
1212
js-sys = "0.3.32"
13+
wasm-bindgen-futures = "0.4.5"

examples/wasm-in-wasm/src/lib.rs

+13-17
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
use js_sys::{Function, Object, Reflect, Uint8Array, WebAssembly};
1+
use js_sys::{Function, Object, Reflect, WebAssembly};
22
use wasm_bindgen::prelude::*;
33
use wasm_bindgen::JsCast;
4+
use wasm_bindgen_futures::{spawn_local, JsFuture};
45

56
// lifted from the `console_log` example
67
#[wasm_bindgen]
@@ -15,24 +16,12 @@ macro_rules! console_log {
1516

1617
const WASM: &[u8] = include_bytes!("add.wasm");
1718

18-
#[wasm_bindgen(start)]
19-
pub fn run() -> Result<(), JsValue> {
19+
async fn run_async() -> Result<(), JsValue> {
2020
console_log!("instantiating a new wasm module directly");
2121

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+
3625
let c = b.exports();
3726

3827
let add = Reflect::get(c.as_ref(), &"add".into())?
@@ -51,3 +40,10 @@ pub fn run() -> Result<(), JsValue> {
5140

5241
Ok(())
5342
}
43+
44+
#[wasm_bindgen(start)]
45+
pub fn run() {
46+
spawn_local(async {
47+
run_async().await.unwrap_throw();
48+
});
49+
}

0 commit comments

Comments
 (0)