Skip to content

Commit

Permalink
Add v8::ArrayBuffer::Data (denoland#1068)
Browse files Browse the repository at this point in the history
  • Loading branch information
littledivy committed Sep 16, 2022
1 parent 780eb79 commit 31291f6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/array_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ extern "C" {
backing_store: *const SharedRef<BackingStore>,
) -> *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(
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,10 @@ two_pointers_t v8__ArrayBuffer__GetBackingStore(const v8::ArrayBuffer& self) {
return make_pod<two_pointers_t>(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();
}
Expand Down
20 changes: 20 additions & 0 deletions tests/test_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 31291f6

Please sign in to comment.