From af187fb357875c7ee80fd4e8cd1fff7161a8faac Mon Sep 17 00:00:00 2001 From: deror1869107 Date: Sun, 5 Feb 2017 00:13:31 +0800 Subject: [PATCH] Add update_raw and update with test --- src/typedarray.rs | 18 +++++++++++++++--- tests/typedarray.rs | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/typedarray.rs b/src/typedarray.rs index 9b23a8f79..52facaa83 100644 --- a/src/typedarray.rs +++ b/src/typedarray.rs @@ -17,6 +17,7 @@ use glue::GetUint8ArrayLengthAndData; use glue::GetUint8ClampedArrayLengthAndData; use jsapi::GetArrayBufferLengthAndData; use jsapi::GetArrayBufferViewLengthAndData; +use jsapi::HandleObject; use jsapi::JSContext; use jsapi::JSObject; use jsapi::JS_GetArrayBufferData; @@ -136,13 +137,24 @@ impl<'a, T: TypedArrayElementCreator + TypedArrayElement> TypedArray<'a, T> { } if let Some(data) = data { - assert!(data.len() <= length as usize); - let buf = T::get_data(result.get()); - ptr::copy_nonoverlapping(data.as_ptr(), buf, data.len()); + TypedArray::::update_raw(data, result.handle()); } Ok(()) } + + /// Update an existed JS typed array + pub unsafe fn update(&mut self, + data: &[T::Element]) { + TypedArray::::update_raw(data, self.object.handle()); + } + + unsafe fn update_raw(data: &[T::Element], + result: HandleObject) { + let (buf, length) = T::length_and_data(result.get()); + assert!(data.len() <= length as usize); + ptr::copy_nonoverlapping(data.as_ptr(), buf, data.len()); + } } /// Internal trait used to associate an element type with an underlying representation diff --git a/tests/typedarray.rs b/tests/typedarray.rs index 03ae3d5b2..3819b0726 100644 --- a/tests/typedarray.rs +++ b/tests/typedarray.rs @@ -46,8 +46,33 @@ fn typedarray() { typedarray!(in(cx) let array: Uint32Array = rval.get()); assert_eq!(array.unwrap().as_slice(), &[1, 3, 5, 0, 0][..]); + typedarray!(in(cx) let mut array: Uint32Array = rval.get()); + array.as_mut().unwrap().update(&[0, 2, 4, 6]); + assert_eq!(array.unwrap().as_slice(), &[0, 2, 4, 6, 0][..]); + rooted!(in(cx) let rval = ptr::null_mut()); typedarray!(in(cx) let array: Uint8Array = rval.get()); assert!(array.is_err()); } } + +#[test] +#[should_panic] +fn typedarray_update_panic() { + let rt = Runtime_::new(); + let cx = rt.cx(); + + unsafe { + rooted!(in(cx) let global = + JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), + OnNewGlobalHookOption::FireOnNewGlobalHook, + &CompartmentOptions::default()) + ); + + let _ac = JSAutoCompartment::new(cx, global.get()); + rooted!(in(cx) let mut rval = ptr::null_mut()); + let _ = Uint32Array::create(cx, 5, Some(&[1, 2, 3, 4, 5]), rval.handle_mut()); + typedarray!(in(cx) let mut array: Uint32Array = rval.get()); + array.as_mut().unwrap().update(&[0, 2, 4, 6, 8, 10]); + } +}