Skip to content

Commit

Permalink
Add TypedArray::copy_from (#2492)
Browse files Browse the repository at this point in the history
* Add TypedArray::copy_from

* Take &self

* Add note about safety

* Remove unnecessary mut
  • Loading branch information
MattiasBuelens authored Mar 16, 2021
1 parent 209d19f commit e6682ca
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
16 changes: 16 additions & 0 deletions crates/js-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4987,6 +4987,22 @@ macro_rules! arrays {
self.raw_copy_to(dst);
}

/// Copy the contents of the source Rust slice into this
/// JS typed array.
///
/// This function will efficiently copy the memory from within
/// the wasm module's own linear memory to this typed array.
///
/// # Panics
///
/// This function will panic if this typed array's length is
/// different than the length of the provided `src` array.
pub fn copy_from(&self, src: &[$ty]) {
assert_eq!(self.length() as usize, src.len());
// This is safe because the `set` function copies from its TypedArray argument
unsafe { self.set(&$name::view(src), 0) }
}

/// Efficiently copies the contents of this JS typed array into a new Vec.
pub fn to_vec(&self) -> Vec<$ty> {
let mut output = vec![$ty::default(); self.length() as usize];
Expand Down
10 changes: 10 additions & 0 deletions crates/js-sys/tests/wasm/TypedArray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ fn copy_to() {
}
}

#[wasm_bindgen_test]
fn copy_from() {
let x = [1, 2, 3];
let array = Int32Array::new(&3.into());
array.copy_from(&x);
array.for_each(&mut |x, i, _| {
assert_eq!(x, (i + 1) as i32);
});
}

#[wasm_bindgen_test]
fn to_vec() {
let array = Int32Array::new(&10.into());
Expand Down

0 comments on commit e6682ca

Please sign in to comment.