koute / stdweb

A standard library for the client-side Web
Apache License 2.0
3.44k stars 177 forks source link

How can I pass an ArrayBuffer from JavaScript to Rust? #193

Open brycefisher opened 6 years ago

brycefisher commented 6 years ago

My end goal is to pass a binary representation of an arbitrary file from a file input from JavaScript into Rust. From looking the docs and examples, I can't see how I might pass this kind of object into Rust. Could you help point me in the right direction? Thanks!!!

Pauan commented 6 years ago

It's hard to give specifics since you haven't given much details about what you're trying to do, but here's the general idea:

use stdweb::web::ArrayBuffer;

fn get_array_buffer() -> Vec<u8> {
    let buffer: ArrayBuffer = js!( return ...; ).try_into().unwrap();
    buffer.into()
}

Replace the ... with the JavaScript code which retrieves the ArrayBuffer

If you want to use a type other than u8 you can use a TypedArray instead, like this:

use stdweb::web::{ArrayBuffer, TypedArray};

fn get_array_buffer() -> Vec<i32> {
    let buffer: ArrayBuffer = js!( return ...; ).try_into().unwrap();
    let buffer: TypedArray<i32> = buffer.into();
    buffer.into()
}

Of course if the JavaScript returns a TypedArray then you can just convert into that directly (you don't need to go through ArrayBuffer first):

use stdweb::web::TypedArray;

fn get_array_buffer() -> Vec<i32> {
    let buffer: TypedArray<i32> = js!( return ...; ).try_into().unwrap();
    buffer.into()
}

I'm assuming that you want to convert it into a type which is usable in Rust (such as Vec<u8>). If you really just want an ArrayBuffer directly you can remove the buffer.into() line (which converts into a Vec<u8>).