Skip to main content

moq_transport/coding/
integer.rs

1use super::{Decode, DecodeError, Encode, EncodeError};
2
3impl Encode for u8 {
4    /// Encode a u8 to the given writer.
5    fn encode<W: bytes::BufMut>(&self, w: &mut W) -> Result<(), EncodeError> {
6        let x = *self;
7        w.put_u8(x);
8        Ok(())
9    }
10}
11
12impl Decode for u8 {
13    fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
14        Self::decode_remaining(r, 1)?;
15        Ok(r.get_u8())
16    }
17}
18
19impl Encode for u16 {
20    /// Encode a u16 to the given writer.
21    fn encode<W: bytes::BufMut>(&self, w: &mut W) -> Result<(), EncodeError> {
22        let x = *self;
23        Self::encode_remaining(w, 2)?;
24        w.put_u16(x);
25        Ok(())
26    }
27}
28
29impl Decode for u16 {
30    fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
31        Self::decode_remaining(r, 2)?;
32        Ok(r.get_u16())
33    }
34}
35
36impl Encode for bool {
37    /// Encode a bool as u8 to the given writer.
38    fn encode<W: bytes::BufMut>(&self, w: &mut W) -> Result<(), EncodeError> {
39        Self::encode_remaining(w, 1)?;
40        let x = *self;
41        match x {
42            true => w.put_u8(1),
43            false => w.put_u8(0),
44        }
45        Ok(())
46    }
47}
48
49impl Decode for bool {
50    fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
51        Self::decode_remaining(r, 1)?;
52        let forward_byte = u8::decode(r)?;
53        match forward_byte {
54            0 => Ok(false),
55            1 => Ok(true),
56            _ => Err(DecodeError::InvalidValue),
57        }
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use bytes::Bytes;
65    use bytes::BytesMut;
66
67    #[test]
68    fn encode_decode_u8() {
69        let mut buf = BytesMut::new();
70
71        let i: u8 = 8;
72        i.encode(&mut buf).unwrap();
73        assert_eq!(buf.to_vec(), vec![0x08]);
74        let decoded = u8::decode(&mut buf).unwrap();
75        assert_eq!(decoded, i);
76    }
77
78    #[test]
79    fn encode_decode_u16() {
80        let mut buf = BytesMut::new();
81
82        let i: u16 = 65534;
83        i.encode(&mut buf).unwrap();
84        assert_eq!(buf.to_vec(), vec![0xff, 0xfe]);
85        let decoded = u16::decode(&mut buf).unwrap();
86        assert_eq!(decoded, i);
87    }
88
89    #[test]
90    fn encode_decode_bool() {
91        let mut buf = BytesMut::new();
92
93        let b = true;
94        b.encode(&mut buf).unwrap();
95        assert_eq!(buf.to_vec(), vec![0x01]);
96        let decoded = bool::decode(&mut buf).unwrap();
97        assert_eq!(decoded, b);
98    }
99
100    #[test]
101    fn decode_invalid_bool() {
102        let data: Vec<u8> = vec![0x02]; // Invalid value for bool
103        let mut buf: Bytes = data.into();
104        let decoded = bool::decode(&mut buf);
105        assert!(matches!(decoded.unwrap_err(), DecodeError::InvalidValue));
106    }
107}