diff --git a/oden-js/src/context.rs b/oden-js/src/context.rs index 7ce96641..b7b09239 100644 --- a/oden-js/src/context.rs +++ b/oden-js/src/context.rs @@ -324,6 +324,34 @@ impl ContextRef { } } + unsafe extern "C" fn free_array_buffer_bytes( + _rt: *mut sys::JSRuntime, + opaque: *mut std::ffi::c_void, + _ptr: *mut std::ffi::c_void, + ) { + drop(Box::from_raw(opaque as *mut Vec)); + } + + pub fn new_array_buffer(&self, buffer: T) -> ValueResult + where + T: Into>, + { + let mut vec_box = Box::new(buffer.into()); + unsafe { + let is_shared = 0; + let byte_ptr = vec_box.as_mut_ptr(); + let byte_len = vec_box.len(); + self.check_exception(sys::JS_NewArrayBuffer( + self.ctx, + byte_ptr, + byte_len, + Some(Self::free_array_buffer_bytes), + Box::into_raw(vec_box) as *mut _, + is_shared, + )) + } + } + /// Fetch the global object for the context. pub fn global_object(&self) -> ValueResult { self.check_exception(unsafe { sys::JS_GetGlobalObject(self.ctx) }) diff --git a/oden-js/src/value.rs b/oden-js/src/value.rs index dfc8d65c..c8a95def 100644 --- a/oden-js/src/value.rs +++ b/oden-js/src/value.rs @@ -323,6 +323,20 @@ impl ValueRef { )) } } + + /// Get the underlying bytes for a an ArrayBuffer object. Obviously it + /// only works if this is an un-detached ArrayBuffer value. + pub fn get_array_buffer<'a>(&'a self, ctx: &ContextRef) -> Result<&'a [u8]> { + unsafe { + let mut size: usize = 0; + let buffer = sys::JS_GetArrayBuffer(ctx.ctx, &mut size as *mut usize, self.val); + if buffer.is_null() { + Err(ctx.exception_error()) + } else { + Ok(std::slice::from_raw_parts(buffer, size)) + } + } + } } impl fmt::Debug for ValueRef {