From c06986c12e987178ec8624d82123725d48403955 Mon Sep 17 00:00:00 2001 From: Marcos Casagrande Date: Sun, 16 Oct 2022 22:03:48 +0200 Subject: [PATCH] feat: add ArrayBuffer::was_detached() (#1103) --- src/array_buffer.rs | 10 ++++++++++ src/binding.cc | 4 ++++ tests/test_api.rs | 10 +++++++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/array_buffer.rs b/src/array_buffer.rs index 99ef6f80..e2edc5d5 100644 --- a/src/array_buffer.rs +++ b/src/array_buffer.rs @@ -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, @@ -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. diff --git a/src/binding.cc b/src/binding.cc index d5344cbe..5804af96 100644 --- a/src/binding.cc +++ b/src/binding.cc @@ -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(); } diff --git a/tests/test_api.rs b/tests/test_api.rs index d4bb9170..602bb8a8 100644 --- a/tests/test_api.rs +++ b/tests/test_api.rs @@ -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());