runestick/
bytes.rs

1//! A container of bytes, corresponding to the [Value::Bytes] type.
2//!
3//! [Value::Bytes]: crate::Value::Bytes.
4
5use crate::{
6    FromValue, InstallWith, Mut, Named, RawMut, RawRef, RawStr, Ref, UnsafeFromValue, Value,
7    VmError,
8};
9
10use std::cmp;
11use std::fmt;
12use std::ops;
13
14/// A vector of bytes.
15#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct Bytes {
17    pub(crate) bytes: Vec<u8>,
18}
19
20impl Bytes {
21    /// Construct a new bytes container.
22    pub const fn new() -> Self {
23        Bytes { bytes: Vec::new() }
24    }
25
26    /// Construct a new bytes container with the specified capacity.
27    pub fn with_capacity(cap: usize) -> Self {
28        Bytes {
29            bytes: Vec::with_capacity(cap),
30        }
31    }
32
33    /// Convert into vector.
34    pub fn into_vec(self) -> Vec<u8> {
35        self.bytes
36    }
37
38    /// Construct from a byte vector.
39    pub fn from_vec(bytes: Vec<u8>) -> Self {
40        Self { bytes }
41    }
42
43    /// Do something with the bytes.
44    pub fn extend(&mut self, other: &Self) {
45        self.bytes.extend(other.bytes.iter().copied());
46    }
47
48    /// Do something with the bytes.
49    pub fn extend_str(&mut self, s: &str) {
50        self.bytes.extend(s.as_bytes());
51    }
52
53    /// Test if the collection is empty.
54    pub fn is_empty(&self) -> bool {
55        self.bytes.is_empty()
56    }
57
58    /// Get the length of the bytes collection.
59    pub fn len(&self) -> usize {
60        self.bytes.len()
61    }
62
63    /// Get the capacity of the bytes collection.
64    pub fn capacity(&self) -> usize {
65        self.bytes.capacity()
66    }
67
68    /// Get the bytes collection.
69    pub fn clear(&mut self) {
70        self.bytes.clear();
71    }
72
73    /// Reserve additional space.
74    ///
75    /// The exact amount is unspecified.
76    pub fn reserve(&mut self, additional: usize) {
77        self.bytes.reserve(additional);
78    }
79
80    /// Resever additional space to the exact amount specified.
81    pub fn reserve_exact(&mut self, additional: usize) {
82        self.bytes.reserve_exact(additional);
83    }
84
85    /// Shrink to fit the amount of bytes in the container.
86    pub fn shrink_to_fit(&mut self) {
87        self.bytes.shrink_to_fit();
88    }
89
90    /// Pop the last byte.
91    pub fn pop(&mut self) -> Option<u8> {
92        self.bytes.pop()
93    }
94
95    /// Access the last byte.
96    pub fn last(&mut self) -> Option<u8> {
97        self.bytes.last().copied()
98    }
99}
100
101impl From<Vec<u8>> for Bytes {
102    fn from(bytes: Vec<u8>) -> Self {
103        Self { bytes }
104    }
105}
106
107impl fmt::Debug for Bytes {
108    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
109        fmt.debug_list().entries(&self.bytes).finish()
110    }
111}
112
113impl ops::Deref for Bytes {
114    type Target = [u8];
115
116    fn deref(&self) -> &Self::Target {
117        &self.bytes
118    }
119}
120
121impl ops::DerefMut for Bytes {
122    fn deref_mut(&mut self) -> &mut Self::Target {
123        &mut self.bytes
124    }
125}
126
127impl FromValue for Bytes {
128    fn from_value(value: Value) -> Result<Self, VmError> {
129        Ok(value.into_bytes()?.borrow_ref()?.clone())
130    }
131}
132
133impl<'a> UnsafeFromValue for &'a Bytes {
134    type Output = *const Bytes;
135    type Guard = RawRef;
136
137    fn from_value(value: Value) -> Result<(Self::Output, Self::Guard), VmError> {
138        let bytes = value.into_bytes()?;
139        let bytes = bytes.into_ref()?;
140        Ok(Ref::into_raw(bytes))
141    }
142
143    unsafe fn unsafe_coerce(output: Self::Output) -> Self {
144        &*output
145    }
146}
147
148impl<'a> UnsafeFromValue for &'a mut Bytes {
149    type Output = *mut Bytes;
150    type Guard = RawMut;
151
152    fn from_value(value: Value) -> Result<(Self::Output, Self::Guard), VmError> {
153        let bytes = value.into_bytes()?;
154        let bytes = bytes.into_mut()?;
155        Ok(Mut::into_raw(bytes))
156    }
157
158    unsafe fn unsafe_coerce(output: Self::Output) -> Self {
159        &mut *output
160    }
161}
162
163impl<'a> UnsafeFromValue for &'a [u8] {
164    type Output = *const [u8];
165    type Guard = RawRef;
166
167    fn from_value(value: Value) -> Result<(Self::Output, Self::Guard), VmError> {
168        let bytes = value.into_bytes()?;
169        let bytes = bytes.into_ref()?;
170        let (value, guard) = Ref::into_raw(bytes);
171        // Safety: we're holding onto the guard for the slice here, so it is
172        // live.
173        Ok((unsafe { (*value).bytes.as_slice() }, guard))
174    }
175
176    unsafe fn unsafe_coerce(output: Self::Output) -> Self {
177        &*output
178    }
179}
180
181impl Named for Bytes {
182    const BASE_NAME: RawStr = RawStr::from_str("Bytes");
183}
184
185impl InstallWith for Bytes {}
186
187impl cmp::PartialEq<[u8]> for Bytes {
188    fn eq(&self, other: &[u8]) -> bool {
189        self.bytes == other
190    }
191}
192
193impl cmp::PartialEq<Bytes> for [u8] {
194    fn eq(&self, other: &Bytes) -> bool {
195        self == other.bytes
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use crate::{Bytes, Shared, Value};
202
203    #[test]
204    fn test_clone_issue() -> Result<(), Box<dyn std::error::Error>> {
205        let shared = Value::Bytes(Shared::new(Bytes::new()));
206
207        let _ = {
208            let shared = shared.into_bytes()?;
209            let out = shared.borrow_ref()?.clone();
210            out
211        };
212
213        Ok(())
214    }
215}