commonware_codec/types/
bytes.rs

1//! Implementations of Codec for byte types.
2//!
3//! For portability and consistency between architectures,
4//! the length of the [`Bytes`] must fit within a [`u32`].
5
6use crate::{util::at_least, EncodeSize, Error, RangeConfig, Read, Write};
7use bytes::{Buf, BufMut, Bytes};
8
9impl Write for Bytes {
10    #[inline]
11    fn write(&self, buf: &mut impl BufMut) {
12        self.len().write(buf);
13        buf.put_slice(self);
14    }
15}
16
17impl EncodeSize for Bytes {
18    #[inline]
19    fn encode_size(&self) -> usize {
20        self.len().encode_size() + self.len()
21    }
22}
23
24impl<R: RangeConfig> Read<R> for Bytes {
25    #[inline]
26    fn read_cfg(buf: &mut impl Buf, range: &R) -> Result<Self, Error> {
27        let len = usize::read_cfg(buf, range)?;
28        at_least(buf, len)?;
29        Ok(buf.copy_to_bytes(len))
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use crate::{Decode, Encode};
37    use bytes::Bytes;
38
39    #[test]
40    fn test_bytes() {
41        let values = [
42            Bytes::new(),
43            Bytes::from_static(&[1, 2, 3]),
44            Bytes::from(vec![0; 300]),
45        ];
46        for value in values {
47            let encoded = value.encode();
48            let len = value.len();
49
50            // Valid decoding
51            let decoded = Bytes::decode_cfg(encoded, &(len..=len)).unwrap();
52            assert_eq!(value, decoded);
53
54            // Failure for too long
55            assert!(matches!(
56                Bytes::decode_cfg(value.encode(), &(0..len)),
57                Err(Error::InvalidLength(_))
58            ));
59
60            // Failure for too short
61            assert!(matches!(
62                Bytes::decode_cfg(value.encode(), &(len + 1..)),
63                Err(Error::InvalidLength(_))
64            ));
65        }
66    }
67}