From 31291f64a64c4e01ff89a42ef337fe42e21922a1 Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Fri, 16 Sep 2022 15:00:05 +0530 Subject: [PATCH] Add `v8::ArrayBuffer::Data` (#1068) --- src/array_buffer.rs | 8 ++++++++ src/binding.cc | 4 ++++ tests/test_api.rs | 20 ++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/src/array_buffer.rs b/src/array_buffer.rs index 5ccf392b..3f8d0d54 100644 --- a/src/array_buffer.rs +++ b/src/array_buffer.rs @@ -36,6 +36,7 @@ extern "C" { backing_store: *const SharedRef, ) -> *const ArrayBuffer; fn v8__ArrayBuffer__Detach(this: *const ArrayBuffer); + fn v8__ArrayBuffer__Data(this: *const ArrayBuffer) -> *mut c_void; fn v8__ArrayBuffer__IsDetachable(this: *const ArrayBuffer) -> bool; fn v8__ArrayBuffer__ByteLength(this: *const ArrayBuffer) -> usize; fn v8__ArrayBuffer__GetBackingStore( @@ -391,6 +392,13 @@ impl ArrayBuffer { } } + /// More efficient shortcut for GetBackingStore()->Data(). + /// The returned pointer is valid as long as the ArrayBuffer is alive. + #[inline] + pub fn data(&self) -> *mut c_void { + unsafe { v8__ArrayBuffer__Data(self) } + } + /// Get a shared pointer to the backing store of this array buffer. This /// pointer coordinates the lifetime management of the internal storage /// with any live ArrayBuffers on the heap, even across isolates. The embedder diff --git a/src/binding.cc b/src/binding.cc index d89aae62..e8a5653b 100644 --- a/src/binding.cc +++ b/src/binding.cc @@ -854,6 +854,10 @@ two_pointers_t v8__ArrayBuffer__GetBackingStore(const v8::ArrayBuffer& self) { return make_pod(ptr_to_local(&self)->GetBackingStore()); } +void* v8__ArrayBuffer__Data(const v8::ArrayBuffer& self) { + return ptr_to_local(&self)->Data(); +} + void v8__ArrayBuffer__Detach(const v8::ArrayBuffer& self) { ptr_to_local(&self)->Detach(); } diff --git a/tests/test_api.rs b/tests/test_api.rs index 429e5a0f..cdbaa4ed 100644 --- a/tests/test_api.rs +++ b/tests/test_api.rs @@ -6678,6 +6678,26 @@ fn backing_store_from_empty_vec() { let _ = v8::ArrayBuffer::with_backing_store(&mut scope, &store); } +#[test] +fn backing_store_data() { + let _setup_guard = setup(); + + let mut isolate = v8::Isolate::new(Default::default()); + let mut scope = v8::HandleScope::new(&mut isolate); + let context = v8::Context::new(&mut scope); + let mut scope = v8::ContextScope::new(&mut scope, context); + + let v = vec![1, 2, 3, 4, 5]; + let len = v.len(); + let store = v8::ArrayBuffer::new_backing_store_from_vec(v).make_shared(); + let buf = v8::ArrayBuffer::with_backing_store(&mut scope, &store); + assert_eq!(buf.byte_length(), len); + assert_eq!( + unsafe { std::slice::from_raw_parts_mut(buf.data() as *mut u8, len) }, + &[1, 2, 3, 4, 5] + ); +} + #[test] fn current_stack_trace() { // Setup isolate