0
0
Fork 0
mirror of https://github.com/denoland/rusty_v8.git synced 2025-01-11 08:34:01 -05:00

Add ArrayBuffer::detach() and is_detachable() (#648)

Fixes #646.
This commit is contained in:
Ben Noordhuis 2021-03-16 23:35:27 +01:00 committed by GitHub
parent 25608cc000
commit 7d514ae4cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 32 additions and 0 deletions

View file

@ -33,6 +33,8 @@ extern "C" {
isolate: *mut Isolate,
backing_store: *const SharedRef<BackingStore>,
) -> *const ArrayBuffer;
fn v8__ArrayBuffer__Detach(this: *const ArrayBuffer);
fn v8__ArrayBuffer__IsDetachable(this: *const ArrayBuffer) -> bool;
fn v8__ArrayBuffer__ByteLength(this: *const ArrayBuffer) -> usize;
fn v8__ArrayBuffer__GetBackingStore(
this: *const ArrayBuffer,
@ -351,6 +353,23 @@ impl ArrayBuffer {
unsafe { v8__ArrayBuffer__ByteLength(self) }
}
/// Returns true if this ArrayBuffer may be detached.
pub fn is_detachable(&self) -> bool {
unsafe { v8__ArrayBuffer__IsDetachable(self) }
}
/// Detaches this ArrayBuffer and all its views (typed arrays).
/// Detaching sets the byte length of the buffer and all typed arrays to zero,
/// preventing JavaScript from ever accessing underlying backing store.
/// ArrayBuffer should have been externalized and must be detachable.
pub fn detach(&self) {
// V8 terminates when the ArrayBuffer is not detachable. Non-detachable
// buffers are buffers that are in use by WebAssembly or asm.js.
if self.is_detachable() {
unsafe { v8__ArrayBuffer__Detach(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

View file

@ -737,6 +737,14 @@ two_pointers_t v8__ArrayBuffer__GetBackingStore(const v8::ArrayBuffer& self) {
return make_pod<two_pointers_t>(ptr_to_local(&self)->GetBackingStore());
}
void v8__ArrayBuffer__Detach(const v8::ArrayBuffer& self) {
ptr_to_local(&self)->Detach();
}
bool v8__ArrayBuffer__IsDetachable(const v8::ArrayBuffer& self) {
return ptr_to_local(&self)->IsDetachable();
}
void* v8__BackingStore__Data(const v8::BackingStore& self) {
return self.Data();
}

View file

@ -439,6 +439,11 @@ fn array_buffer() {
let ab = v8::ArrayBuffer::new(scope, 42);
assert_eq!(42, ab.byte_length());
assert!(ab.is_detachable());
ab.detach();
assert_eq!(0, ab.byte_length());
ab.detach(); // Calling it twice should be a no-op.
let bs = v8::ArrayBuffer::new_backing_store(scope, 84);
assert_eq!(84, bs.byte_length());
assert_eq!(false, bs.is_shared());