Wasm-bindgen: panic on trying to convert ArrayBuffer -> Uint8Array -> Vec<u8>

Created on 13 Jan 2019  路  2Comments  路  Source: rustwasm/wasm-bindgen

I'm using the copy_to method introduced in https://github.com/rustwasm/wasm-bindgen/pull/1147 to try to convert a result from a fetch into an owned Vec<u8>

tihs is the full code:

let window = web_sys::window().unwrap();
let pr = window.fetch_with_str("https://v3-cinemeta.strem.io/catalog/movie/top.json");
let fut = JsFuture::from(pr)
    .and_then(|resp_value| {
    // @TODO: reduce number of copies
    assert!(resp_value.is_instance_of::<Response>());
    let resp: Response = resp_value.dyn_into().unwrap();
    let buf_promise = resp.array_buffer().unwrap();
    JsFuture::from(buf_promise).map(|buf_val| {
        assert!(buf_val.is_instance_of::<ArrayBuffer>());
        let typebuf: js_sys::Uint8Array = js_sys::Uint8Array::new(&buf_val);
        let mut body: Vec<u8> = Vec::with_capacity(typebuf.length() as usize);
        typebuf.copy_to(&mut body);
        body
    })
    })

And this is the result:

wasm-0000006e-3320:2 Uncaught (in promise) RuntimeError: unreachable
    at __rust_start_panic (wasm-function[3320]:1)
    at rust_panic (wasm-function[3319]:31)
    at std::panicking::rust_panic_with_hook::h6143ca5bdd7761ea (wasm-function[3314]:305)
    at std::panicking::continue_panic_fmt::h7ca9995d457595c0 (wasm-function[3313]:116)
    at std::panicking::begin_panic_fmt::h0539ff1194a858ad (wasm-function[3298]:95)
    at js_sys::Uint8Array::copy_to::hf6b245de5260e8be (wasm-function[1831]:563)

What am I missing?

There's a bit of code, given as an example, that seems to do the same here: https://github.com/rustwasm/wasm-bindgen/issues/1160

Most helpful comment

However, this works:

let mut body = vec![0; typebuf.length() as usize];
typebuf.copy_to(&mut body[..]);

I guess the memory needs to be allocated, which makes sense.

However, the copy_to behavior does seem unsafe

All 2 comments

However, this works:

let mut body = vec![0; typebuf.length() as usize];
typebuf.copy_to(&mut body[..]);

I guess the memory needs to be allocated, which makes sense.

However, the copy_to behavior does seem unsafe

Ah yes indeed! As the documentation mentions, the two arrays must have the same length and in the first example the target array has length 0 (with_capacity doesn't allocate any space).

I'd also recommend console_error_panic_hook as that should make the error much more debuggable too!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fitzgen picture fitzgen  路  3Comments

expobrain picture expobrain  路  4Comments

MarcAntoine-Arnaud picture MarcAntoine-Arnaud  路  3Comments

gitmko0 picture gitmko0  路  3Comments

hunterlester picture hunterlester  路  4Comments