2021-01-10 21:59:07 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-09-21 08:26:41 -04:00
|
|
|
|
2020-05-28 13:36:43 -04:00
|
|
|
use crate::bindings;
|
|
|
|
use rusty_v8 as v8;
|
2020-08-18 08:07:57 -04:00
|
|
|
use smallvec::SmallVec;
|
2020-05-28 13:36:43 -04:00
|
|
|
use std::ops::Deref;
|
|
|
|
use std::ops::DerefMut;
|
|
|
|
|
2020-08-18 08:07:57 -04:00
|
|
|
pub type BufVec = SmallVec<[ZeroCopyBuf; 2]>;
|
|
|
|
|
2020-05-28 13:36:43 -04:00
|
|
|
/// A ZeroCopyBuf encapsulates a slice that's been borrowed from a JavaScript
|
|
|
|
/// ArrayBuffer object. JavaScript objects can normally be garbage collected,
|
|
|
|
/// but the existence of a ZeroCopyBuf inhibits this until it is dropped. It
|
2020-07-08 11:23:50 -04:00
|
|
|
/// behaves much like an Arc<[u8]>.
|
|
|
|
///
|
|
|
|
/// # Cloning
|
|
|
|
/// Cloning a ZeroCopyBuf does not clone the contents of the buffer,
|
|
|
|
/// it creates a new reference to that buffer.
|
|
|
|
///
|
|
|
|
/// To actually clone the contents of the buffer do
|
|
|
|
/// `let copy = Vec::from(&*zero_copy_buf);`
|
2020-06-01 14:20:47 -04:00
|
|
|
#[derive(Clone)]
|
2020-05-28 13:36:43 -04:00
|
|
|
pub struct ZeroCopyBuf {
|
|
|
|
backing_store: v8::SharedRef<v8::BackingStore>,
|
|
|
|
byte_offset: usize,
|
|
|
|
byte_length: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe impl Send for ZeroCopyBuf {}
|
|
|
|
|
|
|
|
impl ZeroCopyBuf {
|
2020-06-03 12:19:21 -04:00
|
|
|
pub fn new<'s>(
|
2020-06-20 07:18:08 -04:00
|
|
|
scope: &mut v8::HandleScope<'s>,
|
2020-06-03 12:19:21 -04:00
|
|
|
view: v8::Local<v8::ArrayBufferView>,
|
|
|
|
) -> Self {
|
|
|
|
let backing_store = view.buffer(scope).unwrap().get_backing_store();
|
2020-05-28 13:36:43 -04:00
|
|
|
let byte_offset = view.byte_offset();
|
|
|
|
let byte_length = view.byte_length();
|
|
|
|
Self {
|
|
|
|
backing_store,
|
|
|
|
byte_offset,
|
|
|
|
byte_length,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for ZeroCopyBuf {
|
|
|
|
type Target = [u8];
|
|
|
|
fn deref(&self) -> &[u8] {
|
|
|
|
unsafe {
|
|
|
|
bindings::get_backing_store_slice(
|
|
|
|
&self.backing_store,
|
|
|
|
self.byte_offset,
|
|
|
|
self.byte_length,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for ZeroCopyBuf {
|
|
|
|
fn deref_mut(&mut self) -> &mut [u8] {
|
|
|
|
unsafe {
|
|
|
|
bindings::get_backing_store_slice_mut(
|
|
|
|
&self.backing_store,
|
|
|
|
self.byte_offset,
|
|
|
|
self.byte_length,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsRef<[u8]> for ZeroCopyBuf {
|
|
|
|
fn as_ref(&self) -> &[u8] {
|
|
|
|
&*self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsMut<[u8]> for ZeroCopyBuf {
|
|
|
|
fn as_mut(&mut self) -> &mut [u8] {
|
|
|
|
&mut *self
|
|
|
|
}
|
|
|
|
}
|