Skip to content

Commit e6682ca

Browse files
Add TypedArray::copy_from (#2492)
* Add TypedArray::copy_from * Take &self * Add note about safety * Remove unnecessary mut
1 parent 209d19f commit e6682ca

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

crates/js-sys/src/lib.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4987,6 +4987,22 @@ macro_rules! arrays {
49874987
self.raw_copy_to(dst);
49884988
}
49894989

4990+
/// Copy the contents of the source Rust slice into this
4991+
/// JS typed array.
4992+
///
4993+
/// This function will efficiently copy the memory from within
4994+
/// the wasm module's own linear memory to this typed array.
4995+
///
4996+
/// # Panics
4997+
///
4998+
/// This function will panic if this typed array's length is
4999+
/// different than the length of the provided `src` array.
5000+
pub fn copy_from(&self, src: &[$ty]) {
5001+
assert_eq!(self.length() as usize, src.len());
5002+
// This is safe because the `set` function copies from its TypedArray argument
5003+
unsafe { self.set(&$name::view(src), 0) }
5004+
}
5005+
49905006
/// Efficiently copies the contents of this JS typed array into a new Vec.
49915007
pub fn to_vec(&self) -> Vec<$ty> {
49925008
let mut output = vec![$ty::default(); self.length() as usize];

crates/js-sys/tests/wasm/TypedArray.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,16 @@ fn copy_to() {
145145
}
146146
}
147147

148+
#[wasm_bindgen_test]
149+
fn copy_from() {
150+
let x = [1, 2, 3];
151+
let array = Int32Array::new(&3.into());
152+
array.copy_from(&x);
153+
array.for_each(&mut |x, i, _| {
154+
assert_eq!(x, (i + 1) as i32);
155+
});
156+
}
157+
148158
#[wasm_bindgen_test]
149159
fn to_vec() {
150160
let array = Int32Array::new(&10.into());

0 commit comments

Comments
 (0)