litep2p/codec/
unsigned_varint.rs

1// Copyright 2023 litep2p developers
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! [`unsigned-varint`](https://github.com/multiformats/unsigned-varint) codec.
22
23use crate::error::Error;
24
25use bytes::{Bytes, BytesMut};
26use tokio_util::codec::{Decoder, Encoder};
27use unsigned_varint::codec::UviBytes;
28
29/// Unsigned varint codec.
30pub struct UnsignedVarint {
31    codec: UviBytes<bytes::Bytes>,
32}
33
34impl UnsignedVarint {
35    /// Create new [`UnsignedVarint`] codec.
36    pub fn new(max_size: Option<usize>) -> Self {
37        let mut codec = UviBytes::<Bytes>::default();
38
39        if let Some(max_size) = max_size {
40            codec.set_max_len(max_size);
41        }
42
43        Self { codec }
44    }
45
46    /// Set maximum size for encoded/decodes values.
47    pub fn with_max_size(max_size: usize) -> Self {
48        let mut codec = UviBytes::<Bytes>::default();
49        codec.set_max_len(max_size);
50
51        Self { codec }
52    }
53
54    /// Encode `payload` using `unsigned-varint`.
55    pub fn encode<T: Into<Bytes>>(payload: T) -> crate::Result<Vec<u8>> {
56        let payload: Bytes = payload.into();
57
58        assert!(payload.len() <= u32::MAX as usize);
59
60        let mut bytes = BytesMut::with_capacity(payload.len() + 4);
61        let mut codec = Self::new(None);
62        codec.encode(payload, &mut bytes)?;
63
64        Ok(bytes.into())
65    }
66
67    /// Decode `payload` into `BytesMut`.
68    pub fn decode(payload: &mut BytesMut) -> crate::Result<BytesMut> {
69        UviBytes::<Bytes>::default().decode(payload)?.ok_or(Error::InvalidData)
70    }
71}
72
73impl Decoder for UnsignedVarint {
74    type Item = BytesMut;
75    type Error = Error;
76
77    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
78        self.codec.decode(src).map_err(From::from)
79    }
80}
81
82impl Encoder<Bytes> for UnsignedVarint {
83    type Error = Error;
84
85    fn encode(&mut self, item: Bytes, dst: &mut bytes::BytesMut) -> Result<(), Self::Error> {
86        self.codec.encode(item, dst).map_err(From::from)
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::{Bytes, BytesMut, UnsignedVarint};
93
94    #[test]
95    fn max_size_respected() {
96        let mut codec = UnsignedVarint::with_max_size(1024);
97
98        {
99            use tokio_util::codec::Encoder;
100
101            let bytes_to_encode: Bytes = vec![0u8; 1024].into();
102            let mut out_bytes = BytesMut::with_capacity(2048);
103            assert!(codec.encode(bytes_to_encode, &mut out_bytes).is_ok());
104        }
105
106        {
107            use tokio_util::codec::Encoder;
108
109            let bytes_to_encode: Bytes = vec![1u8; 1025].into();
110            let mut out_bytes = BytesMut::with_capacity(2048);
111            assert!(codec.encode(bytes_to_encode, &mut out_bytes).is_err());
112        }
113    }
114
115    #[test]
116    fn encode_decode_works() {
117        let encoded1 = UnsignedVarint::encode(vec![0u8; 512]).unwrap();
118        let mut encoded2 = {
119            use tokio_util::codec::Encoder;
120
121            let mut codec = UnsignedVarint::with_max_size(512);
122            let bytes_to_encode: Bytes = vec![0u8; 512].into();
123            let mut out_bytes = BytesMut::with_capacity(2048);
124            codec.encode(bytes_to_encode, &mut out_bytes).unwrap();
125            out_bytes
126        };
127
128        assert_eq!(encoded1, encoded2);
129
130        let decoded1 = UnsignedVarint::decode(&mut encoded2).unwrap();
131        let decoded2 = {
132            use tokio_util::codec::Decoder;
133
134            let mut codec = UnsignedVarint::with_max_size(512);
135            let mut encoded1 = BytesMut::from(&encoded1[..]);
136            codec.decode(&mut encoded1).unwrap().unwrap()
137        };
138
139        assert_eq!(decoded1, decoded2);
140    }
141}