Skip to main content

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<usize>;
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
83    #[cfg(feature = "arbitrary")]
84    mod conformance {
85        use super::*;
86        use crate::conformance::CodecConformance;
87        use arbitrary::Arbitrary;
88
89        /// Newtype wrapper to implement Arbitrary for [super::Bytes].
90        #[derive(Debug)]
91        struct Bytes(super::Bytes);
92
93        impl Write for Bytes {
94            fn write(&self, buf: &mut impl BufMut) {
95                self.0.write(buf);
96            }
97        }
98
99        impl EncodeSize for Bytes {
100            fn encode_size(&self) -> usize {
101                self.0.encode_size()
102            }
103        }
104
105        impl Read for Bytes {
106            type Cfg = RangeCfg<usize>;
107
108            fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, Error> {
109                Ok(Self(super::Bytes::read_cfg(buf, cfg)?))
110            }
111        }
112
113        impl Arbitrary<'_> for Bytes {
114            fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
115                let len = u.arbitrary::<u8>()?;
116                let bytes: Vec<u8> = u
117                    .arbitrary_iter()?
118                    .take(len as usize)
119                    .collect::<Result<Vec<_>, _>>()
120                    .unwrap();
121                Ok(Self(super::Bytes::from(bytes)))
122            }
123        }
124
125        commonware_conformance::conformance_tests! {
126            CodecConformance<Bytes>
127        }
128    }
129}