How can a Vec be returned as a typed array with wasm-bindgen?

6.8k views Asked by At

I have a Vec I would like to return and convert to a typed array with wasm-bindgen, ie, to turn a Vec<u32> into a Uint32Array. From my research it appears that wasm-bindgen cannot handle automatically converting these by itself right now (like it does for String) and instead you must use the js-sys crate. I haven't found clear examples of how to use this crate however. It would be much appreciated if a clear simple example of how to use it could be provided.

For completeness' sake, it would be great if answers could explain both how to expose a function returning a Vec<u32>, as well as a struct member, ie, how do you convert these definitions into something that will work:

#[wasm_bindgen]
pub fn my_func() -> Vec<u32> {
    inner_func() // returns Vec<u32>
}

#[wasm_bindgen]
pub struct my_struct {
    #[wasm_bindgen(readonly)]
    pub my_vec: Vec<u32>,
}
1

There are 1 answers

7
MaxV On BEST ANSWER

You can convert a Vec<u32> to a js_sys::Uint32Array. So your my_func would look like:

#[wasm_bindgen]
pub fn my_func() -> js_sys::Uint32Array {
    let rust_array = inner_func();
    return js_sys::Uint32Array::from(&rust_array[..]);
}

And the struct can be exposed by making a getter:

#[wasm_bindgen]
pub struct my_struct {
    // Note: not pub
    my_vec: Vec<u32>,
}

#[wasm_bindgen]
impl my_struct {
    #[wasm_bindgen(getter)]
    pub fn my_vec(&self) -> js_sys::Uint32Array {
        return js_sys::Uint32Array::from(&self.my_vec[..]);
    }
}