0
0
Fork 0
mirror of https://github.com/denoland/rusty_v8.git synced 2024-11-24 15:19:31 -05:00

feat: add scope-less data() access on ArrayBufferView (#1338)

This commit is contained in:
Matt Mastracci 2023-09-29 18:20:29 -06:00 committed by GitHub
parent 768e598831
commit 12dca0cf03
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 4 deletions

View file

@ -11,6 +11,9 @@ extern "C" {
fn v8__ArrayBufferView__Buffer(
this: *const ArrayBufferView,
) -> *const ArrayBuffer;
fn v8__ArrayBufferView__Buffer__Data(
this: *const ArrayBufferView,
) -> *mut c_void;
fn v8__ArrayBufferView__ByteLength(this: *const ArrayBufferView) -> usize;
fn v8__ArrayBufferView__ByteOffset(this: *const ArrayBufferView) -> usize;
fn v8__ArrayBufferView__CopyContents(
@ -30,6 +33,17 @@ impl ArrayBufferView {
unsafe { scope.cast_local(|_| v8__ArrayBufferView__Buffer(self)) }
}
/// Returns the underlying storage for this `ArrayBufferView`, including the built-in `byte_offset`.
/// This is a more efficient way of calling `buffer(scope)->data()`, and may be called without a
/// scope.
#[inline(always)]
pub fn data(&self) -> *mut c_void {
unsafe {
v8__ArrayBufferView__Buffer__Data(self)
.add(v8__ArrayBufferView__ByteOffset(self))
}
}
/// Size of a view in bytes.
#[inline(always)]
pub fn byte_length(&self) -> usize {

View file

@ -1657,6 +1657,11 @@ const v8::ArrayBuffer* v8__ArrayBufferView__Buffer(
return local_to_ptr(ptr_to_local(&self)->Buffer());
}
const void* v8__ArrayBufferView__Buffer__Data(
const v8::ArrayBufferView& self) {
return ptr_to_local(&self)->Buffer()->Data();
}
size_t v8__ArrayBufferView__ByteLength(const v8::ArrayBufferView& self) {
return ptr_to_local(&self)->ByteLength();
}

View file

@ -5022,22 +5022,32 @@ fn array_buffer_view() {
let scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(scope);
let scope = &mut v8::ContextScope::new(scope, context);
let source =
v8::String::new(scope, "new Uint8Array([23,23,23,23])").unwrap();
let source = v8::String::new(
scope,
"new Uint8Array(new Uint8Array([22,22,23,23,23,23]).buffer, 2, 4)",
)
.unwrap();
let script = v8::Script::compile(scope, source, None).unwrap();
source.to_rust_string_lossy(scope);
let result: v8::Local<v8::ArrayBufferView> =
script.run(scope).unwrap().try_into().unwrap();
assert_eq!(result.byte_length(), 4);
assert_eq!(result.byte_offset(), 0);
assert_eq!(result.byte_offset(), 2);
let mut dest = [0; 4];
let copy_bytes = result.copy_contents(&mut dest);
assert_eq!(copy_bytes, 4);
assert_eq!(dest, [23, 23, 23, 23]);
let slice = unsafe {
std::slice::from_raw_parts(
result.data() as *const u8,
result.byte_length(),
)
};
assert_eq!(dest, slice);
let maybe_ab = result.buffer(scope);
assert!(maybe_ab.is_some());
let ab = maybe_ab.unwrap();
assert_eq!(ab.byte_length(), 4);
assert_eq!(ab.byte_length(), 6);
}
}