Pass file from Javascript to u8 in Rust WebAssembly

Viewed 1171

I want to pass through a file from JavaScript and get access to it as a u8 array in Rust WebAssembly. I have done this in Emscripten c++ buffer by allocating memory and passing pointer but I can't fathom it in RUST and wasm-bindgen.

1 Answers

If you expose a function with an arg data: &[u8]

#[wasm_bindgen]
#[allow(non_snake_case)]
#[no_mangle]
pub fn processFile(fileData: &[u8])

You can pass a byte array to it from JavaScript

let fileData = new Uint8Array(23);
// populate data ...
mod.processFile(fileData)

Perhaps just with the version I'm using

λ wasm-pack -V
wasm-pack 0.8.1

Array length might be an issue, (my code has fixed length data) I would pass the len in the function and validate it because I'm not sure how rustc could validate that otherwise.

Related