Use a length accessor instead of byteLength

This way we should be naturally compatible with normal JS arrays that get passed
in as well!

Closes #133
This commit is contained in:
Alex Crichton 2018-04-16 13:49:47 -07:00
parent bd755c0378
commit 0e032955fb
2 changed files with 55 additions and 5 deletions

View File

@ -672,7 +672,7 @@ impl<'a> Context<'a> {
self.expose_uint8_memory();
self.global(&format!("
function passArray8ToWasm(arg) {{
const ptr = wasm.__wbindgen_malloc(arg.byteLength);
const ptr = wasm.__wbindgen_malloc(arg.length);
getUint8Memory().set(arg, ptr);
return [ptr, arg.length];
}}
@ -687,7 +687,7 @@ impl<'a> Context<'a> {
self.expose_uint16_memory();
self.global(&format!("
function passArray16ToWasm(arg) {{
const ptr = wasm.__wbindgen_malloc(arg.byteLength);
const ptr = wasm.__wbindgen_malloc(arg.length * 2);
getUint16Memory().set(arg, ptr / 2);
return [ptr, arg.length];
}}
@ -702,7 +702,7 @@ impl<'a> Context<'a> {
self.expose_uint32_memory();
self.global(&format!("
function passArray32ToWasm(arg) {{
const ptr = wasm.__wbindgen_malloc(arg.byteLength);
const ptr = wasm.__wbindgen_malloc(arg.length * 4);
getUint32Memory().set(arg, ptr / 4);
return [ptr, arg.length];
}}
@ -716,7 +716,7 @@ impl<'a> Context<'a> {
self.required_internal_exports.insert("__wbindgen_malloc");
self.global(&format!("
function passArrayF32ToWasm(arg) {{
const ptr = wasm.__wbindgen_malloc(arg.byteLength);
const ptr = wasm.__wbindgen_malloc(arg.length * 4);
new Float32Array(wasm.memory.buffer).set(arg, ptr / 4);
return [ptr, arg.length];
}}
@ -730,7 +730,7 @@ impl<'a> Context<'a> {
self.required_internal_exports.insert("__wbindgen_malloc");
self.global(&format!("
function passArrayF64ToWasm(arg) {{
const ptr = wasm.__wbindgen_malloc(arg.byteLength);
const ptr = wasm.__wbindgen_malloc(arg.length * 8);
new Float64Array(wasm.memory.buffer).set(arg, ptr / 8);
return [ptr, arg.length];
}}

View File

@ -228,3 +228,53 @@ fn import() {
"#)
.test();
}
#[test]
fn pass_array_works() {
project()
.file("src/lib.rs", r#"
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
macro_rules! doit {
($(($rust:ident, $i:ident))*) => ($(
#[wasm_bindgen]
pub fn $rust(a: &[$i]) {
assert_eq!(a.len(), 2);
assert_eq!(a[0], 1 as $i);
assert_eq!(a[1], 2 as $i);
}
)*)
}
doit! {
(rust_i8, i8)
(rust_u8, u8)
(rust_i16, i16)
(rust_u16, u16)
(rust_i32, i32)
(rust_u32, u32)
(rust_f32, f32)
(rust_f64, f64)
}
"#)
.file("test.js", r#"
const wasm = require("./out");
module.exports.test = function() {
wasm.rust_i8([1, 2]);
wasm.rust_u8([1, 2]);
wasm.rust_i16([1, 2]);
wasm.rust_u16([1, 2]);
wasm.rust_i32([1, 2]);
wasm.rust_u32([1, 2]);
wasm.rust_f32([1, 2]);
wasm.rust_f64([1, 2]);
};
"#)
.test();
}