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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use std::mem::size_of;
use std::ops::Deref;
use std::ops::DerefMut;

use smallvec::SmallVec;

use super::transl8::FromV8;
use super::transl8::ToV8;
use crate::magic::transl8::impl_magic;
use crate::Error;

const USIZE2X: usize = size_of::<usize>() * 2;

#[derive(PartialEq, Eq, Clone, Debug, Default)]
pub struct ByteString(SmallVec<[u8; USIZE2X]>);
impl_magic!(ByteString);

impl Deref for ByteString {
  type Target = SmallVec<[u8; USIZE2X]>;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl DerefMut for ByteString {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

impl AsRef<[u8]> for ByteString {
  fn as_ref(&self) -> &[u8] {
    &self.0
  }
}

impl AsMut<[u8]> for ByteString {
  fn as_mut(&mut self) -> &mut [u8] {
    &mut self.0
  }
}

// const-assert that Vec<u8> and SmallVec<[u8; size_of::<usize>() * 2]> have a same size.
// Note from https://docs.rs/smallvec/latest/smallvec/#union -
//   smallvec can still be larger than Vec if the inline buffer is
//   larger than two machine words.
const _: () =
  assert!(size_of::<Vec<u8>>() == size_of::<SmallVec<[u8; USIZE2X]>>());

impl ToV8 for ByteString {
  fn to_v8<'a>(
    &self,
    scope: &mut v8::HandleScope<'a>,
  ) -> Result<v8::Local<'a, v8::Value>, crate::Error> {
    let v =
      v8::String::new_from_one_byte(scope, self, v8::NewStringType::Normal)
        .unwrap();
    Ok(v.into())
  }
}

impl FromV8 for ByteString {
  fn from_v8(
    scope: &mut v8::HandleScope,
    value: v8::Local<v8::Value>,
  ) -> Result<Self, crate::Error> {
    let v8str = v8::Local::<v8::String>::try_from(value)
      .map_err(|_| Error::ExpectedString(value.type_repr()))?;
    if !v8str.contains_only_onebyte() {
      return Err(Error::ExpectedLatin1);
    }
    let len = v8str.length();
    let mut buffer = SmallVec::with_capacity(len);
    #[allow(clippy::uninit_vec)]
    // SAFETY: we set length == capacity (see previous line),
    // before immediately writing into that buffer and sanity check with an assert
    unsafe {
      buffer.set_len(len);
      let written = v8str.write_one_byte(
        scope,
        &mut buffer,
        0,
        v8::WriteOptions::NO_NULL_TERMINATION,
      );
      assert!(written == len);
    }
    Ok(Self(buffer))
  }
}

// smallvec does not impl From/Into traits
// like Vec<u8> does. So here we are.

impl From<Vec<u8>> for ByteString {
  fn from(vec: Vec<u8>) -> Self {
    ByteString(SmallVec::from_vec(vec))
  }
}

#[allow(clippy::from_over_into)]
impl Into<Vec<u8>> for ByteString {
  fn into(self) -> Vec<u8> {
    self.0.into_vec()
  }
}

impl From<&[u8]> for ByteString {
  fn from(s: &[u8]) -> Self {
    ByteString(SmallVec::from_slice(s))
  }
}

impl From<&str> for ByteString {
  fn from(s: &str) -> Self {
    let v: Vec<u8> = s.into();
    ByteString::from(v)
  }
}

impl From<String> for ByteString {
  fn from(s: String) -> Self {
    ByteString::from(s.into_bytes())
  }
}