2019-12-09 18:44:49 +01:00
|
|
|
use js_sys::{Function, Object, Reflect, WebAssembly};
|
2018-03-22 17:39:48 -07:00
|
|
|
use wasm_bindgen::prelude::*;
|
2018-09-20 16:20:42 -07:00
|
|
|
use wasm_bindgen::JsCast;
|
2019-12-09 18:44:49 +01:00
|
|
|
use wasm_bindgen_futures::{spawn_local, JsFuture};
|
2018-03-22 17:39:48 -07:00
|
|
|
|
2018-09-20 16:20:42 -07:00
|
|
|
// lifted from the `console_log` example
|
2018-03-22 17:39:48 -07:00
|
|
|
#[wasm_bindgen]
|
2018-06-27 22:42:34 -07:00
|
|
|
extern "C" {
|
2018-03-22 17:39:48 -07:00
|
|
|
#[wasm_bindgen(js_namespace = console)]
|
|
|
|
fn log(a: &str);
|
|
|
|
}
|
|
|
|
|
2018-09-20 16:20:42 -07:00
|
|
|
macro_rules! console_log {
|
2018-03-22 17:39:48 -07:00
|
|
|
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
|
|
|
|
}
|
|
|
|
|
|
|
|
const WASM: &[u8] = include_bytes!("add.wasm");
|
|
|
|
|
2019-12-09 18:44:49 +01:00
|
|
|
async fn run_async() -> Result<(), JsValue> {
|
2018-09-20 16:20:42 -07:00
|
|
|
console_log!("instantiating a new wasm module directly");
|
2019-02-19 13:27:30 -08:00
|
|
|
|
2019-12-09 18:44:49 +01:00
|
|
|
let a = JsFuture::from(WebAssembly::instantiate_buffer(WASM, &Object::new())).await?;
|
|
|
|
let b: WebAssembly::Instance = Reflect::get(&a, &"instance".into())?.dyn_into()?;
|
|
|
|
|
2018-03-22 17:39:48 -07:00
|
|
|
let c = b.exports();
|
|
|
|
|
2018-09-25 11:55:28 -07:00
|
|
|
let add = Reflect::get(c.as_ref(), &"add".into())?
|
2018-09-20 16:20:42 -07:00
|
|
|
.dyn_into::<Function>()
|
|
|
|
.expect("add export wasn't a function");
|
|
|
|
|
|
|
|
let three = add.call2(&JsValue::undefined(), &1.into(), &2.into())?;
|
|
|
|
console_log!("1 + 2 = {:?}", three);
|
2018-09-25 11:55:28 -07:00
|
|
|
let mem = Reflect::get(c.as_ref(), &"memory".into())?
|
2018-09-20 16:20:42 -07:00
|
|
|
.dyn_into::<WebAssembly::Memory>()
|
|
|
|
.expect("memory export wasn't a `WebAssembly.Memory`");
|
|
|
|
console_log!("created module has {} pages of memory", mem.grow(0));
|
|
|
|
console_log!("giving the module 4 more pages of memory");
|
2018-03-22 17:39:48 -07:00
|
|
|
mem.grow(4);
|
2018-09-20 16:20:42 -07:00
|
|
|
console_log!("now the module has {} pages of memory", mem.grow(0));
|
|
|
|
|
|
|
|
Ok(())
|
2018-03-22 17:39:48 -07:00
|
|
|
}
|
2019-12-09 18:44:49 +01:00
|
|
|
|
|
|
|
#[wasm_bindgen(start)]
|
|
|
|
pub fn run() {
|
|
|
|
spawn_local(async {
|
|
|
|
run_async().await.unwrap_throw();
|
|
|
|
});
|
|
|
|
}
|