summavy_ownedbytes/
lib.rs

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