From 5e88b1ecaba425ad9b7d371471ba54e5d9866da9 Mon Sep 17 00:00:00 2001 From: Pauan Date: Mon, 24 Jun 2019 18:21:12 +0200 Subject: [PATCH] Updating a couple examples --- examples/wasm-in-wasm/src/lib.rs | 5 +++-- examples/webgl/src/lib.rs | 25 +++++++++++++++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/examples/wasm-in-wasm/src/lib.rs b/examples/wasm-in-wasm/src/lib.rs index 4a4ab5536c66..eecc527a2843 100644 --- a/examples/wasm-in-wasm/src/lib.rs +++ b/examples/wasm-in-wasm/src/lib.rs @@ -19,18 +19,19 @@ const WASM: &[u8] = include_bytes!("add.wasm"); pub fn run() -> Result<(), JsValue> { console_log!("instantiating a new wasm module directly"); - // Note that `Uint8Array::view` this is somewhat dangerous (hence the + // Note that `Uint8Array::view` is somewhat dangerous (hence the // `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 - // do any memory allocations before it's next used. + // do any memory allocations before it's dropped. let a = unsafe { let array = Uint8Array::view(WASM); WebAssembly::Module::new(array.as_ref())? }; + let b = WebAssembly::Instance::new(&a, &Object::new())?; let c = b.exports(); diff --git a/examples/webgl/src/lib.rs b/examples/webgl/src/lib.rs index f73532f48a57..37acafa38371 100644 --- a/examples/webgl/src/lib.rs +++ b/examples/webgl/src/lib.rs @@ -39,12 +39,25 @@ pub fn start() -> Result<(), JsValue> { let buffer = context.create_buffer().ok_or("failed to create buffer")?; context.bind_buffer(WebGlRenderingContext::ARRAY_BUFFER, Some(&buffer)); - let vert_array = unsafe { js_sys::Float32Array::view(&vertices) }; - context.buffer_data_with_array_buffer_view( - WebGlRenderingContext::ARRAY_BUFFER, - &vert_array, - WebGlRenderingContext::STATIC_DRAW, - ); + + // Note that `Float32Array::view` is somewhat dangerous (hence the + // `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 `Float32Array` to be invalid. + // + // As a result, after `Float32Array::view` we have to be very careful not to + // do any memory allocations before it's dropped. + unsafe { + let vert_array = js_sys::Float32Array::view(&vertices); + + context.buffer_data_with_array_buffer_view( + WebGlRenderingContext::ARRAY_BUFFER, + &vert_array, + WebGlRenderingContext::STATIC_DRAW, + ); + } + context.vertex_attrib_pointer_with_i32(0, 3, WebGlRenderingContext::FLOAT, false, 0, 0); context.enable_vertex_attrib_array(0);