length_delimited/
bytes.rs

1use dbutils::{
2  error::{IncompleteBuffer, InsufficientBuffer},
3  leb128::*,
4};
5
6use crate::{LengthDelimitedDecoder, LengthDelimitedEncoder};
7
8macro_rules! bytes_impl {
9  ($($ty:ty:$from_bytes:ident), +$(,)?) => {
10    bytes_impl!(@encoder $($ty), +);
11    bytes_impl!(@decoder $($ty:$from_bytes), +);
12  };
13  (@encoder $($ty:ty), +$(,)?) => {
14    $(
15      impl $crate::LengthDelimitedEncoder for $ty {
16        type Error = $crate::InsufficientBuffer;
17
18        fn encoded_len(&self) -> usize {
19          let buf: &[u8] = self.as_ref();
20          buf.len()
21        }
22
23        fn encoded_length_delimited_len(&self) -> usize {
24          let buf: &[u8] = self.as_ref();
25          let len = buf.len();
26          encoded_u64_varint_len(len as u64) + len
27        }
28
29        fn encode_length_delimited(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
30          let dst_len = buf.len();
31          let this: &[u8] = self.as_ref();
32          let len = this.len();
33
34          let written = match ::dbutils::leb128::Varint::encode(&(len as u64), buf) {
35            Ok(written) => written,
36            Err(_) => {
37              return Err(InsufficientBuffer::with_information(
38                self.encoded_length_delimited_len() as u64,
39                dst_len as u64,
40              ));
41            }
42          };
43
44          self.encode(&mut buf[written..])
45            .map(|bytes| written + bytes)
46            .map_err(|_| InsufficientBuffer::with_information(
47              (written + len) as u64,
48              dst_len as u64,
49            ))
50        }
51
52        fn encode(
53          &self,
54          buf: &mut [u8],
55        ) -> Result<usize, Self::Error> {
56          let dst_len = buf.len();
57          let this: &[u8] = self.as_ref();
58          let len = this.len();
59
60          let required = len;
61          if required > dst_len {
62            return Err(InsufficientBuffer::with_information(required as u64, dst_len as u64));
63          }
64
65          buf[..required].copy_from_slice(this);
66          Ok(required)
67        }
68      }
69    )*
70  };
71  (@decoder $($ty:ty:$from_bytes:ident), +$(,)?) => {
72    $(
73      impl $crate::LengthDelimitedDecoder for $ty {
74        type Error = $crate::DecodeBytesError;
75
76        fn decode(src: &[u8]) -> Result<(usize, Self), Self::Error>
77        where
78          Self: Sized
79        {
80          Ok((src.len(), Self::$from_bytes(src)))
81        }
82
83        fn decode_length_delimited(src: &[u8]) -> Result<(usize, Self), Self::Error>
84        where
85          Self: Sized {
86          let (read, val) = decode_u64_varint(src)?;
87          let len = val as usize;
88          let required = read + len;
89          if required > src.len() {
90            return Err(IncompleteBuffer::with_information(required as u64, src.len() as u64).into());
91          }
92
93          Self::decode(&src[read..required]).map(|(bytes, this)| (read + bytes, this))
94        }
95      }
96    )*
97  };
98}
99
100bytes_impl!(@encoder &[u8]);
101
102#[cfg(any(feature = "std", feature = "alloc"))]
103bytes_impl!(std::vec::Vec<u8>:from, std::boxed::Box<[u8]>:from, std::sync::Arc<[u8]>:from, std::rc::Rc<[u8]>:from);
104
105#[cfg(all(feature = "triomphe01", any(feature = "std", feature = "alloc")))]
106bytes_impl!(triomphe01::Arc<[u8]>:from,);
107
108#[cfg(all(feature = "bytes1", any(feature = "std", feature = "alloc")))]
109bytes_impl!(bytes1::Bytes:copy_from_slice,);
110
111#[cfg(all(feature = "bstr1", any(feature = "std", feature = "alloc")))]
112bytes_impl!(bstr1::BString:from,);
113
114#[cfg(feature = "bstr1")]
115bytes_impl!(@encoder &bstr1::BStr,);
116
117impl<const N: usize> LengthDelimitedEncoder for [u8; N] {
118  type Error = InsufficientBuffer;
119
120  fn encoded_len(&self) -> usize {
121    N
122  }
123
124  fn encoded_length_delimited_len(&self) -> usize {
125    N
126  }
127
128  fn encode_length_delimited(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
129    self.encode(buf)
130  }
131
132  fn encode(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
133    if buf.len() < N {
134      return Err(InsufficientBuffer::with_information(
135        N as u64,
136        buf.len() as u64,
137      ));
138    }
139
140    buf[..N].copy_from_slice(self);
141    Ok(N)
142  }
143}
144
145impl<const N: usize> LengthDelimitedDecoder for [u8; N] {
146  type Error = DecodeBytesError;
147
148  fn decode(src: &[u8]) -> Result<(usize, Self), Self::Error>
149  where
150    Self: Sized,
151  {
152    let len = src.len();
153    if len < N {
154      return Err(DecodeBytesError::IncompleteBuffer(
155        IncompleteBuffer::with_information(N as u64, len as u64),
156      ));
157    }
158
159    let mut dst = [0; N];
160    dst.copy_from_slice(&src[..N]);
161    Ok((N, dst))
162  }
163
164  fn decode_length_delimited(src: &[u8]) -> Result<(usize, Self), Self::Error>
165  where
166    Self: Sized,
167  {
168    Self::decode(src)
169  }
170}
171
172/// The error that can be returned when decoding bytes.
173#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
174pub enum DecodeBytesError {
175  /// Returned when there is not enough data to decode the full type.
176  #[error(transparent)]
177  IncompleteBuffer(#[from] IncompleteBuffer),
178  /// Returned when the length delimited overflows.
179  #[error("length delimited overflow")]
180  Overflow,
181}
182
183impl From<DecodeVarintError> for DecodeBytesError {
184  fn from(e: DecodeVarintError) -> Self {
185    match e {
186      DecodeVarintError::Underflow => Self::IncompleteBuffer(IncompleteBuffer::new()),
187      DecodeVarintError::Overflow => Self::Overflow,
188    }
189  }
190}