izihawa_ownedbytes/
lib.rs

1use std::ops::{Deref, Range};
2use std::sync::Arc;
3use std::{fmt, io};
4
5pub use stable_deref_trait::StableDeref;
6
7/// An OwnedBytes simply wraps an object that owns a slice of data and exposes
8/// this data as a slice.
9///
10/// The backing object is required to be `StableDeref`.
11#[derive(Clone)]
12pub struct OwnedBytes {
13    data: &'static [u8],
14    box_stable_deref: Arc<dyn Deref<Target = [u8]> + Sync + Send>,
15}
16
17impl OwnedBytes {
18    /// Creates an empty `OwnedBytes`.
19    pub fn empty() -> OwnedBytes {
20        OwnedBytes::new(&[][..])
21    }
22
23    /// Creates an `OwnedBytes` instance given a `StableDeref` object.
24    pub fn new<T: StableDeref + Deref<Target = [u8]> + 'static + Send + Sync>(
25        data_holder: T,
26    ) -> OwnedBytes {
27        let box_stable_deref = Arc::new(data_holder);
28        let bytes: &[u8] = box_stable_deref.deref();
29        let data = unsafe { &*(bytes as *const [u8]) };
30        OwnedBytes {
31            data,
32            box_stable_deref,
33        }
34    }
35
36    /// creates a fileslice that is just a view over a slice of the data.
37    #[must_use]
38    #[inline]
39    pub fn slice(&self, range: Range<usize>) -> Self {
40        OwnedBytes {
41            data: &self.data[range],
42            box_stable_deref: self.box_stable_deref.clone(),
43        }
44    }
45
46    /// Returns the underlying slice of data.
47    /// `Deref` and `AsRef` are also available.
48    #[inline]
49    pub fn as_slice(&self) -> &[u8] {
50        self.data
51    }
52
53    /// Returns the len of the slice.
54    #[inline]
55    pub fn len(&self) -> usize {
56        self.data.len()
57    }
58
59    /// Returns true iff this `OwnedBytes` is empty.
60    #[inline]
61    pub fn is_empty(&self) -> bool {
62        self.data.is_empty()
63    }
64
65    /// Splits the OwnedBytes into two OwnedBytes `(left, right)`.
66    ///
67    /// Left will hold `split_len` bytes.
68    ///
69    /// This operation is cheap and does not require to copy any memory.
70    /// On the other hand, both `left` and `right` retain a handle over
71    /// the entire slice of memory. In other words, the memory will only
72    /// be released when both left and right are dropped.
73    #[inline]
74    #[must_use]
75    pub fn split(self, split_len: usize) -> (OwnedBytes, OwnedBytes) {
76        let (left_data, right_data) = self.data.split_at(split_len);
77        let right_box_stable_deref = self.box_stable_deref.clone();
78        let left = OwnedBytes {
79            data: left_data,
80            box_stable_deref: self.box_stable_deref,
81        };
82        let right = OwnedBytes {
83            data: right_data,
84            box_stable_deref: right_box_stable_deref,
85        };
86        (left, right)
87    }
88
89    /// Splits the OwnedBytes into two OwnedBytes `(left, right)`.
90    ///
91    /// Right will hold `split_len` bytes.
92    ///
93    /// This operation is cheap and does not require to copy any memory.
94    /// On the other hand, both `left` and `right` retain a handle over
95    /// the entire slice of memory. In other words, the memory will only
96    /// be released when both left and right are dropped.
97    #[inline]
98    #[must_use]
99    pub fn rsplit(self, split_len: usize) -> (OwnedBytes, OwnedBytes) {
100        let data_len = self.data.len();
101        self.split(data_len - split_len)
102    }
103
104    /// Splits the right part of the `OwnedBytes` at the given offset.
105    ///
106    /// `self` is truncated to `split_len`, left with the remaining bytes.
107    pub fn split_off(&mut self, split_len: usize) -> OwnedBytes {
108        let (left, right) = self.data.split_at(split_len);
109        let right_box_stable_deref = self.box_stable_deref.clone();
110        let right_piece = OwnedBytes {
111            data: right,
112            box_stable_deref: right_box_stable_deref,
113        };
114        self.data = left;
115        right_piece
116    }
117
118    /// Drops the left most `advance_len` bytes.
119    #[inline]
120    pub fn advance(&mut self, advance_len: usize) -> &[u8] {
121        let (data, rest) = self.data.split_at(advance_len);
122        self.data = rest;
123        data
124    }
125
126    /// Reads an `u8` from the `OwnedBytes` and advance by one byte.
127    #[inline]
128    pub fn read_u8(&mut self) -> u8 {
129        self.advance(1)[0]
130    }
131
132    #[inline]
133    fn read_n<const N: usize>(&mut self) -> [u8; N] {
134        self.advance(N).try_into().unwrap()
135    }
136
137    /// Reads an `u32` encoded as little-endian from the `OwnedBytes` and advance by 4 bytes.
138    #[inline]
139    pub fn read_u32(&mut self) -> u32 {
140        u32::from_le_bytes(self.read_n())
141    }
142
143    /// Reads an `u64` encoded as little-endian from the `OwnedBytes` and advance by 8 bytes.
144    #[inline]
145    pub fn read_u64(&mut self) -> u64 {
146        u64::from_le_bytes(self.read_n())
147    }
148}
149
150impl fmt::Debug for OwnedBytes {
151    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152        // We truncate the bytes in order to make sure the debug string
153        // is not too long.
154        let bytes_truncated: &[u8] = if self.len() > 10 {
155            &self.as_slice()[..10]
156        } else {
157            self.as_slice()
158        };
159        write!(f, "OwnedBytes({bytes_truncated:?}, len={})", self.len())
160    }
161}
162
163impl PartialEq for OwnedBytes {
164    fn eq(&self, other: &OwnedBytes) -> bool {
165        self.as_slice() == other.as_slice()
166    }
167}
168
169impl Eq for OwnedBytes {}
170
171impl PartialEq<[u8]> for OwnedBytes {
172    fn eq(&self, other: &[u8]) -> bool {
173        self.as_slice() == other
174    }
175}
176
177impl PartialEq<str> for OwnedBytes {
178    fn eq(&self, other: &str) -> bool {
179        self.as_slice() == other.as_bytes()
180    }
181}
182
183impl<'a, T: ?Sized> PartialEq<&'a T> for OwnedBytes
184where
185    OwnedBytes: PartialEq<T>,
186{
187    fn eq(&self, other: &&'a T) -> bool {
188        *self == **other
189    }
190}
191
192impl Deref for OwnedBytes {
193    type Target = [u8];
194
195    #[inline]
196    fn deref(&self) -> &Self::Target {
197        self.as_slice()
198    }
199}
200
201impl AsRef<[u8]> for OwnedBytes {
202    #[inline]
203    fn as_ref(&self) -> &[u8] {
204        self.as_slice()
205    }
206}
207
208impl io::Read for OwnedBytes {
209    #[inline]
210    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
211        let data_len = self.data.len();
212        let buf_len = buf.len();
213        if data_len >= buf_len {
214            let data = self.advance(buf_len);
215            buf.copy_from_slice(data);
216            Ok(buf_len)
217        } else {
218            buf[..data_len].copy_from_slice(self.data);
219            self.data = &[];
220            Ok(data_len)
221        }
222    }
223    #[inline]
224    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
225        buf.extend(self.data);
226        let read_len = self.data.len();
227        self.data = &[];
228        Ok(read_len)
229    }
230    #[inline]
231    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
232        let read_len = self.read(buf)?;
233        if read_len != buf.len() {
234            return Err(io::Error::new(
235                io::ErrorKind::UnexpectedEof,
236                "failed to fill whole buffer",
237            ));
238        }
239        Ok(())
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use std::io::{self, Read};
246
247    use super::OwnedBytes;
248
249    #[test]
250    fn test_owned_bytes_debug() {
251        let short_bytes = OwnedBytes::new(b"abcd".as_ref());
252        assert_eq!(
253            format!("{short_bytes:?}"),
254            "OwnedBytes([97, 98, 99, 100], len=4)"
255        );
256        let medium_bytes = OwnedBytes::new(b"abcdefghi".as_ref());
257        assert_eq!(
258            format!("{medium_bytes:?}"),
259            "OwnedBytes([97, 98, 99, 100, 101, 102, 103, 104, 105], len=9)"
260        );
261        let long_bytes = OwnedBytes::new(b"abcdefghijklmnopq".as_ref());
262        assert_eq!(
263            format!("{long_bytes:?}"),
264            "OwnedBytes([97, 98, 99, 100, 101, 102, 103, 104, 105, 106], len=17)"
265        );
266    }
267
268    #[test]
269    fn test_owned_bytes_read() -> io::Result<()> {
270        let mut bytes = OwnedBytes::new(b"abcdefghiklmnopqrstuvwxyz".as_ref());
271        {
272            let mut buf = [0u8; 5];
273            bytes.read_exact(&mut buf[..]).unwrap();
274            assert_eq!(&buf, b"abcde");
275            assert_eq!(bytes.as_slice(), b"fghiklmnopqrstuvwxyz")
276        }
277        {
278            let mut buf = [0u8; 2];
279            bytes.read_exact(&mut buf[..]).unwrap();
280            assert_eq!(&buf, b"fg");
281            assert_eq!(bytes.as_slice(), b"hiklmnopqrstuvwxyz")
282        }
283        Ok(())
284    }
285
286    #[test]
287    fn test_owned_bytes_read_right_at_the_end() -> io::Result<()> {
288        let mut bytes = OwnedBytes::new(b"abcde".as_ref());
289        let mut buf = [0u8; 5];
290        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 5);
291        assert_eq!(&buf, b"abcde");
292        assert_eq!(bytes.as_slice(), b"");
293        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 0);
294        assert_eq!(&buf, b"abcde");
295        Ok(())
296    }
297    #[test]
298    fn test_owned_bytes_read_incomplete() -> io::Result<()> {
299        let mut bytes = OwnedBytes::new(b"abcde".as_ref());
300        let mut buf = [0u8; 7];
301        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 5);
302        assert_eq!(&buf[..5], b"abcde");
303        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 0);
304        Ok(())
305    }
306
307    #[test]
308    fn test_owned_bytes_read_to_end() -> io::Result<()> {
309        let mut bytes = OwnedBytes::new(b"abcde".as_ref());
310        let mut buf = Vec::new();
311        bytes.read_to_end(&mut buf)?;
312        assert_eq!(buf.as_slice(), b"abcde".as_ref());
313        Ok(())
314    }
315
316    #[test]
317    fn test_owned_bytes_read_u8() -> io::Result<()> {
318        let mut bytes = OwnedBytes::new(b"\xFF".as_ref());
319        assert_eq!(bytes.read_u8(), 255);
320        assert_eq!(bytes.len(), 0);
321        Ok(())
322    }
323
324    #[test]
325    fn test_owned_bytes_read_u64() -> io::Result<()> {
326        let mut bytes = OwnedBytes::new(b"\0\xFF\xFF\xFF\xFF\xFF\xFF\xFF".as_ref());
327        assert_eq!(bytes.read_u64(), u64::MAX - 255);
328        assert_eq!(bytes.len(), 0);
329        Ok(())
330    }
331
332    #[test]
333    fn test_owned_bytes_split() {
334        let bytes = OwnedBytes::new(b"abcdefghi".as_ref());
335        let (left, right) = bytes.split(3);
336        assert_eq!(left.as_slice(), b"abc");
337        assert_eq!(right.as_slice(), b"defghi");
338    }
339
340    #[test]
341    fn test_owned_bytes_split_boundary() {
342        let bytes = OwnedBytes::new(b"abcdefghi".as_ref());
343        {
344            let (left, right) = bytes.clone().split(0);
345            assert_eq!(left.as_slice(), b"");
346            assert_eq!(right.as_slice(), b"abcdefghi");
347        }
348        {
349            let (left, right) = bytes.split(9);
350            assert_eq!(left.as_slice(), b"abcdefghi");
351            assert_eq!(right.as_slice(), b"");
352        }
353    }
354
355    #[test]
356    fn test_split_off() {
357        let mut data = OwnedBytes::new(b"abcdef".as_ref());
358        assert_eq!(data, "abcdef");
359        assert_eq!(data.split_off(2), "cdef");
360        assert_eq!(data, "ab");
361        assert_eq!(data.split_off(1), "b");
362        assert_eq!(data, "a");
363    }
364}