Skip to content

TypedArray::from(slice) sporadically fails #4492

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

Open
rkreis-v opened this issue Apr 28, 2025 · 1 comment
Open

TypedArray::from(slice) sporadically fails #4492

rkreis-v opened this issue Apr 28, 2025 · 1 comment
Labels

Comments

@rkreis-v
Copy link

rkreis-v commented Apr 28, 2025

Describe the Bug

Closely related to #4395 - TypedArray::from with slice input sporadically fails: "Cannot perform Construct on a detached ArrayBuffer". It uses TypedArray::view:

impl<'a> From<&'a [$ty]> for $name {
#[inline]
fn from(slice: &'a [$ty]) -> $name {
// This is safe because the `new` function makes a copy if its argument is a TypedArray
unsafe { $name::new(&$name::view(slice)) }
}
}

Note that the function is not marked unsafe itself.

Steps to Reproduce

Add test case to crates/js-sys/tests/wasm/TypedArray.rs:

#[wasm_bindgen_test]
fn from_succeeds_when_heap_grows() {
    let _ = (0..10_000).map(|i| {
        Int32Array::from([i].as_slice())
    }).collect::<Vec<_>>();
}

Run test:

# cargo test --target wasm32-unknown-unknown from_succeeds_when_heap_grows
[...]
running 1 test
test TypedArray::from_succeeds_when_heap_grows ... FAIL

failures:

---- TypedArray::from_succeeds_when_heap_grows output ----
    error output:
        wasm-bindgen: imported JS function that was not marked as `catch` threw an error: Cannot perform Construct on a detached ArrayBuffer

        Stack:
        TypeError: Cannot perform Construct on a detached ArrayBuffer
            at new Int32Array (<anonymous>)
@rkreis-v rkreis-v added the bug label Apr 28, 2025
@Spxg
Copy link
Contributor

Spxg commented May 23, 2025

Copying an js array in rust is fragile and hard to fix, so the solution is to copy it on the js side.

Try this: https://github.com/Spxg/wasm-array-cp

#[wasm_bindgen_test]
fn from_succeeds_when_heap_grows() {
    let _ = (0..10_000)
        .map(|i| ArrayBufferCopy::from_slice([i].as_slice()))
        .collect::<Vec<Int32Array>>();
}

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

No branches or pull requests

2 participants