Skip to content

Add TypedArray::copy_from #2492

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

Merged
merged 4 commits into from
Mar 16, 2021

Conversation

MattiasBuelens
Copy link
Contributor

This introduces TypedArray::copy_from(src), as the dual of TypedArray::copy_to(dst).

While this can already be achieved today with TypedArray::set(), it requires either unsafe code or an additional allocation:

let x = [1, 2, 3];
let mut array = Int32Array::new(&3.into());

unsafe { array.set(Int32Array::view(&x), 0); } // view() is unsafe
// or
array.set(Int32Array::from(&x), 0); // from() allocates a new Uint8Array to copy the contents of x

The new helper method provides a safe interface to perform this copy:

let x = [1, 2, 3];
let mut array = Int32Array::new(&3.into());
array.copy_from(&x);

Internally, it uses the unsafe implementation listed above. We know that this is safe, because:

  • the TypedArray view on the Rust slice lives only for the duration of the copy_from() call
  • set() does not grow the WebAssembly linear memory, so it cannot invalidate the created view

@alexcrichton
Copy link
Contributor

Looks good to me, thanks! I think that the method should probably take &self instead of &mut self as well since it's all JS, but otherwise seems good to go.

@alexcrichton alexcrichton merged commit e6682ca into rustwasm:master Mar 16, 2021
@MattiasBuelens MattiasBuelens deleted the typed-array-copy-from branch March 16, 2021 21:31
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

Successfully merging this pull request may close these issues.

2 participants