Skip to main content

ld_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 OwnedBytes: PartialEq<T>
185{
186    fn eq(&self, other: &&'a T) -> bool {
187        *self == **other
188    }
189}
190
191impl Deref for OwnedBytes {
192    type Target = [u8];
193
194    #[inline]
195    fn deref(&self) -> &Self::Target {
196        self.as_slice()
197    }
198}
199
200impl AsRef<[u8]> for OwnedBytes {
201    #[inline]
202    fn as_ref(&self) -> &[u8] {
203        self.as_slice()
204    }
205}
206
207impl io::Read for OwnedBytes {
208    #[inline]
209    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
210        let data_len = self.data.len();
211        let buf_len = buf.len();
212        if data_len >= buf_len {
213            let data = self.advance(buf_len);
214            buf.copy_from_slice(data);
215            Ok(buf_len)
216        } else {
217            buf[..data_len].copy_from_slice(self.data);
218            self.data = &[];
219            Ok(data_len)
220        }
221    }
222    #[inline]
223    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
224        buf.extend(self.data);
225        let read_len = self.data.len();
226        self.data = &[];
227        Ok(read_len)
228    }
229    #[inline]
230    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
231        let read_len = self.read(buf)?;
232        if read_len != buf.len() {
233            return Err(io::Error::new(
234                io::ErrorKind::UnexpectedEof,
235                "failed to fill whole buffer",
236            ));
237        }
238        Ok(())
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 medium_bytes = OwnedBytes::new(b"abcdefghi".as_ref());
256        assert_eq!(
257            format!("{medium_bytes:?}"),
258            "OwnedBytes([97, 98, 99, 100, 101, 102, 103, 104, 105], len=9)"
259        );
260        let long_bytes = OwnedBytes::new(b"abcdefghijklmnopq".as_ref());
261        assert_eq!(
262            format!("{long_bytes:?}"),
263            "OwnedBytes([97, 98, 99, 100, 101, 102, 103, 104, 105, 106], len=17)"
264        );
265    }
266
267    #[test]
268    fn test_owned_bytes_read() -> io::Result<()> {
269        let mut bytes = OwnedBytes::new(b"abcdefghiklmnopqrstuvwxyz".as_ref());
270        {
271            let mut buf = [0u8; 5];
272            bytes.read_exact(&mut buf[..]).unwrap();
273            assert_eq!(&buf, b"abcde");
274            assert_eq!(bytes.as_slice(), b"fghiklmnopqrstuvwxyz")
275        }
276        {
277            let mut buf = [0u8; 2];
278            bytes.read_exact(&mut buf[..]).unwrap();
279            assert_eq!(&buf, b"fg");
280            assert_eq!(bytes.as_slice(), b"hiklmnopqrstuvwxyz")
281        }
282        Ok(())
283    }
284
285    #[test]
286    fn test_owned_bytes_read_right_at_the_end() -> io::Result<()> {
287        let mut bytes = OwnedBytes::new(b"abcde".as_ref());
288        let mut buf = [0u8; 5];
289        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 5);
290        assert_eq!(&buf, b"abcde");
291        assert_eq!(bytes.as_slice(), b"");
292        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 0);
293        assert_eq!(&buf, b"abcde");
294        Ok(())
295    }
296    #[test]
297    fn test_owned_bytes_read_incomplete() -> io::Result<()> {
298        let mut bytes = OwnedBytes::new(b"abcde".as_ref());
299        let mut buf = [0u8; 7];
300        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 5);
301        assert_eq!(&buf[..5], b"abcde");
302        assert_eq!(bytes.read(&mut buf[..]).unwrap(), 0);
303        Ok(())
304    }
305
306    #[test]
307    fn test_owned_bytes_read_to_end() -> io::Result<()> {
308        let mut bytes = OwnedBytes::new(b"abcde".as_ref());
309        let mut buf = Vec::new();
310        bytes.read_to_end(&mut buf)?;
311        assert_eq!(buf.as_slice(), b"abcde".as_ref());
312        Ok(())
313    }
314
315    #[test]
316    fn test_owned_bytes_read_u8() -> io::Result<()> {
317        let mut bytes = OwnedBytes::new(b"\xFF".as_ref());
318        assert_eq!(bytes.read_u8(), 255);
319        assert_eq!(bytes.len(), 0);
320        Ok(())
321    }
322
323    #[test]
324    fn test_owned_bytes_read_u64() -> io::Result<()> {
325        let mut bytes = OwnedBytes::new(b"\0\xFF\xFF\xFF\xFF\xFF\xFF\xFF".as_ref());
326        assert_eq!(bytes.read_u64(), u64::MAX - 255);
327        assert_eq!(bytes.len(), 0);
328        Ok(())
329    }
330
331    #[test]
332    fn test_owned_bytes_split() {
333        let bytes = OwnedBytes::new(b"abcdefghi".as_ref());
334        let (left, right) = bytes.split(3);
335        assert_eq!(left.as_slice(), b"abc");
336        assert_eq!(right.as_slice(), b"defghi");
337    }
338
339    #[test]
340    fn test_owned_bytes_split_boundary() {
341        let bytes = OwnedBytes::new(b"abcdefghi".as_ref());
342        {
343            let (left, right) = bytes.clone().split(0);
344            assert_eq!(left.as_slice(), b"");
345            assert_eq!(right.as_slice(), b"abcdefghi");
346        }
347        {
348            let (left, right) = bytes.split(9);
349            assert_eq!(left.as_slice(), b"abcdefghi");
350            assert_eq!(right.as_slice(), b"");
351        }
352    }
353
354    #[test]
355    fn test_split_off() {
356        let mut data = OwnedBytes::new(b"abcdef".as_ref());
357        assert_eq!(data, "abcdef");
358        assert_eq!(data.split_off(2), "cdef");
359        assert_eq!(data, "ab");
360        assert_eq!(data.split_off(1), "b");
361        assert_eq!(data, "a");
362    }
363}