derse/
deserializer.rs

1use std::borrow::Cow;
2
3use super::{Error, Result};
4
5/// A trait for deserializing data from a byte slice.
6pub trait Deserializer<'a> {
7    /// Checks if the deserializer is empty.
8    fn is_empty(&self) -> bool;
9
10    /// Advances the deserializer by the specified length.
11    ///
12    /// # Errors
13    ///
14    /// Returns an error if the length to advance exceeds the available data.
15    fn advance(&mut self, len: usize) -> Result<Self>
16    where
17        Self: Sized;
18
19    /// Pops the specified length of data from the deserializer.
20    ///
21    /// # Errors
22    ///
23    /// Returns an error if the length to pop exceeds the available data.
24    fn pop(&mut self, len: usize) -> Result<Cow<'a, [u8]>>;
25}
26
27/// Implements the `Deserializer` trait for a byte slice.
28impl<'a> Deserializer<'a> for &'a [u8] {
29    /// Checks if the byte slice is empty.
30    fn is_empty(&self) -> bool {
31        <[u8]>::is_empty(self)
32    }
33
34    /// Advances the byte slice by the specified length.
35    ///
36    /// # Errors
37    ///
38    /// Returns an error if the length to advance exceeds the available data.
39    fn advance(&mut self, len: usize) -> Result<Self>
40    where
41        Self: Sized,
42    {
43        if len <= self.len() {
44            let (front, back) = self.split_at(len);
45            *self = back;
46            Ok(front)
47        } else {
48            Err(Error::DataIsShort {
49                expect: len,
50                actual: self.len(),
51            })
52        }
53    }
54
55    /// Pops the specified length of data from the byte slice.
56    ///
57    /// # Errors
58    ///
59    /// Returns an error if the length to pop exceeds the available data.
60    fn pop(&mut self, len: usize) -> Result<Cow<'a, [u8]>> {
61        if len <= self.len() {
62            let (front, back) = self.split_at(len);
63            *self = back;
64            Ok(Cow::Borrowed(front))
65        } else {
66            Err(Error::DataIsShort {
67                expect: len,
68                actual: self.len(),
69            })
70        }
71    }
72}