Skip to content

Commit

Permalink
feat: add ArrayBuffer::was_detached() (denoland#1103)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcosc90 committed Oct 16, 2022
1 parent 09cac0a commit c06986c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/array_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ extern "C" {
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__WasDetached(this: *const ArrayBuffer) -> bool;
fn v8__ArrayBuffer__ByteLength(this: *const ArrayBuffer) -> usize;
fn v8__ArrayBuffer__GetBackingStore(
this: *const ArrayBuffer,
Expand Down Expand Up @@ -389,6 +390,15 @@ impl ArrayBuffer {
unsafe { v8__ArrayBuffer__IsDetachable(self) }
}

/// Returns true if this ArrayBuffer was detached.
#[inline(always)]
pub fn was_detached(&self) -> bool {
if self.byte_length() != 0 {
return false;
}
unsafe { v8__ArrayBuffer__WasDetached(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.
Expand Down
4 changes: 4 additions & 0 deletions src/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,10 @@ bool v8__ArrayBuffer__IsDetachable(const v8::ArrayBuffer& self) {
return ptr_to_local(&self)->IsDetachable();
}

bool v8__ArrayBuffer__WasDetached(const v8::ArrayBuffer& self) {
return v8::Utils::OpenHandle(&self)->was_detached();
}

void* v8__BackingStore__Data(const v8::BackingStore& self) {
return self.Data();
}
Expand Down
10 changes: 9 additions & 1 deletion tests/test_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,12 +573,20 @@ fn array_buffer() {

let ab = v8::ArrayBuffer::new(scope, 42);
assert_eq!(42, ab.byte_length());

assert!(!ab.was_detached());
assert!(ab.is_detachable());

ab.detach();
assert_eq!(0, ab.byte_length());
assert!(ab.was_detached());
ab.detach(); // Calling it twice should be a no-op.

// detecting if it was detached on a zero-length ArrayBuffer should work
let empty_ab = v8::ArrayBuffer::new(scope, 0);
assert!(!empty_ab.was_detached());
empty_ab.detach();
assert!(empty_ab.was_detached());

let bs = v8::ArrayBuffer::new_backing_store(scope, 84);
assert_eq!(84, bs.byte_length());
assert!(!bs.is_shared());
Expand Down

0 comments on commit c06986c

Please sign in to comment.