Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

panic on trying to convert ArrayBuffer -> Uint8Array -> Vec<u8> #1171

Closed
Ivshti opened this issue Jan 13, 2019 · 2 comments
Closed

panic on trying to convert ArrayBuffer -> Uint8Array -> Vec<u8> #1171

Ivshti opened this issue Jan 13, 2019 · 2 comments

Comments

@Ivshti
Copy link
Contributor

Ivshti commented Jan 13, 2019

I'm using the copy_to method introduced in #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: #1160

@Ivshti
Copy link
Contributor Author

Ivshti commented Jan 13, 2019

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

@alexcrichton
Copy link
Contributor

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants