2018-09-25 11:55:28 -07:00
|
|
|
use js_sys::{Function, Object, Reflect, Uint8Array, 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;
|
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");
|
|
|
|
|
2018-11-28 09:25:51 -08:00
|
|
|
#[wasm_bindgen(start)]
|
2018-09-20 16:20:42 -07:00
|
|
|
pub fn run() -> Result<(), JsValue> {
|
|
|
|
console_log!("instantiating a new wasm module directly");
|
2019-02-19 13:27:30 -08:00
|
|
|
|
2019-06-24 18:21:12 +02:00
|
|
|
// Note that `Uint8Array::view` is somewhat dangerous (hence the
|
2019-02-19 13:27:30 -08:00
|
|
|
// `unsafe`!). This is creating a raw view into our module's
|
|
|
|
// `WebAssembly.Memory` buffer, but if we allocate more pages for ourself
|
|
|
|
// (aka do a memory allocation in Rust) it'll cause the buffer to change,
|
|
|
|
// causing the `Uint8Array` to be invalid.
|
|
|
|
//
|
|
|
|
// As a result, after `Uint8Array::view` we have to be very careful not to
|
2019-06-24 18:21:12 +02:00
|
|
|
// do any memory allocations before it's dropped.
|
2019-02-19 13:27:30 -08:00
|
|
|
let a = unsafe {
|
|
|
|
let array = Uint8Array::view(WASM);
|
|
|
|
WebAssembly::Module::new(array.as_ref())?
|
|
|
|
};
|
2019-06-24 18:21:12 +02:00
|
|
|
|
2018-09-20 16:20:42 -07:00
|
|
|
let b = WebAssembly::Instance::new(&a, &Object::new())?;
|
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
|
|
|
}
|