deno.land / x / deno@v1.28.2 / serde_v8 / magic / string_or_buffer.rs

string_or_buffer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.use super::buffer::ZeroCopyBuf;use super::transl8::{FromV8, ToV8};use crate::magic::transl8::impl_magic;use crate::Error;use std::ops::Deref;
#[derive(Debug)]pub enum StringOrBuffer { Buffer(ZeroCopyBuf), String(String),}
impl_magic!(StringOrBuffer);
impl Deref for StringOrBuffer { type Target = [u8]; fn deref(&self) -> &Self::Target { match self { Self::Buffer(b) => b.as_ref(), Self::String(s) => s.as_bytes(), } }}
impl ToV8 for StringOrBuffer { fn to_v8<'a>( &mut self, scope: &mut v8::HandleScope<'a>, ) -> Result<v8::Local<'a, v8::Value>, crate::Error> { match self { Self::Buffer(buf) => { let buf: Box<[u8]> = match buf { ZeroCopyBuf::FromV8(buf) => { let value: &[u8] = buf; value.into() } ZeroCopyBuf::Temp(_) => unreachable!(), ZeroCopyBuf::ToV8(ref mut x) => { x.take().expect("ZeroCopyBuf was empty") } }; let backing_store = v8::ArrayBuffer::new_backing_store_from_boxed_slice(buf); Ok( v8::ArrayBuffer::with_backing_store(scope, &backing_store.into()) .into(), ) } Self::String(s) => crate::to_v8(scope, s), } }}
impl FromV8 for StringOrBuffer { fn from_v8( scope: &mut v8::HandleScope, value: v8::Local<v8::Value>, ) -> Result<Self, crate::Error> { if let Ok(buf) = ZeroCopyBuf::from_v8(scope, value) { return Ok(Self::Buffer(buf)); } else if let Ok(s) = crate::from_v8(scope, value) { return Ok(Self::String(s)); } Err(Error::ExpectedBuffer) }}
impl From<StringOrBuffer> for bytes::Bytes { fn from(sob: StringOrBuffer) -> Self { match sob { StringOrBuffer::Buffer(b) => b.into(), StringOrBuffer::String(s) => s.into_bytes().into(), } }}
deno

Version Info

Tagged at
a year ago