1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-01 16:51:13 -05:00
denoland-deno/serde_v8/magic/detached_buffer.rs
Bartek Iwańczuk b88b7c9244
chore: upgrade rusty_v8 to 0.55.0 (#16604)
<!--
Before submitting a PR, please read http://deno.land/manual/contributing

1. Give the PR a descriptive title.

  Examples of good title:
    - fix(std/http): Fix race condition in server
    - docs(console): Update docstrings
    - feat(doc): Handle nested reexports

  Examples of bad title:
    - fix #7123
    - update docs
    - fix bugs

2. Ensure there is a related issue and it is referenced in the PR text.
3. Ensure there are tests that cover the changes.
4. Ensure `cargo test` passes.
5. Ensure `./tools/format.js` passes without changing files.
6. Ensure `./tools/lint.js` passes.
-->
2022-11-12 05:37:37 +01:00

69 lines
1.7 KiB
Rust

// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use core::ops::Range;
use std::ops::Deref;
use std::ops::DerefMut;
use super::transl8::FromV8;
use super::transl8::ToV8;
use super::v8slice::to_ranged_buffer;
use super::v8slice::V8Slice;
use crate::magic::transl8::impl_magic;
// A buffer that detaches when deserialized from JS
pub struct DetachedBuffer(V8Slice);
impl_magic!(DetachedBuffer);
impl AsRef<[u8]> for DetachedBuffer {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsMut<[u8]> for DetachedBuffer {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut()
}
}
impl Deref for DetachedBuffer {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.0.deref()
}
}
impl DerefMut for DetachedBuffer {
fn deref_mut(&mut self) -> &mut [u8] {
self.0.deref_mut()
}
}
impl ToV8 for DetachedBuffer {
fn to_v8<'a>(
&mut self,
scope: &mut v8::HandleScope<'a>,
) -> Result<v8::Local<'a, v8::Value>, crate::Error> {
let buffer = v8::ArrayBuffer::with_backing_store(scope, &self.0.store);
let Range { start, end } = self.0.range;
let (off, len) = (start, end - start);
let v = v8::Uint8Array::new(scope, buffer, off, len).unwrap();
Ok(v.into())
}
}
impl FromV8 for DetachedBuffer {
fn from_v8(
scope: &mut v8::HandleScope,
value: v8::Local<v8::Value>,
) -> Result<Self, crate::Error> {
let (b, range) =
to_ranged_buffer(scope, value).or(Err(crate::Error::ExpectedBuffer))?;
if !b.is_detachable() {
return Err(crate::Error::ExpectedDetachable);
}
let store = b.get_backing_store();
b.detach(v8::undefined(scope).into()); // Detach
Ok(Self(V8Slice { store, range }))
}
}