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, RangeCfg, 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 Read for Bytes {
25    type Cfg = RangeCfg;
26
27    #[inline]
28    fn read_cfg(buf: &mut impl Buf, range: &Self::Cfg) -> Result<Self, Error> {
29        let len = usize::read_cfg(buf, range)?;
30        at_least(buf, len)?;
31        Ok(buf.copy_to_bytes(len))
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use crate::{Decode, Encode};
39    use bytes::Bytes;
40
41    #[test]
42    fn test_bytes() {
43        let values = [
44            Bytes::new(),
45            Bytes::from_static(&[1, 2, 3]),
46            Bytes::from(vec![0; 300]),
47        ];
48        for value in values {
49            let encoded = value.encode();
50            let len = value.len();
51
52            // Valid decoding
53            let decoded = Bytes::decode_cfg(encoded, &(len..=len).into()).unwrap();
54            assert_eq!(value, decoded);
55
56            // Failure for too long
57            assert!(matches!(
58                Bytes::decode_cfg(value.encode(), &(0..len).into()),
59                Err(Error::InvalidLength(_))
60            ));
61
62            // Failure for too short
63            assert!(matches!(
64                Bytes::decode_cfg(value.encode(), &(len + 1..).into()),
65                Err(Error::InvalidLength(_))
66            ));
67        }
68    }
69
70    #[test]
71    fn test_conformity() {
72        assert_eq!(Bytes::new().encode(), &[0x00][..]);
73        assert_eq!(
74            Bytes::from_static(b"hello").encode(),
75            &[0x05, b'h', b'e', b'l', b'l', b'o'][..]
76        );
77        let long_bytes = Bytes::from(vec![0xAA; 150]);
78        let mut expected = vec![0x96, 0x01]; // Varint for 150
79        expected.extend_from_slice(&[0xAA; 150]);
80        assert_eq!(long_bytes.encode(), expected.as_slice());
81    }
82}