Skip to main content

moq_transport/coding/
string.rs

1// TODO SLG - eventually remove this file, bounded_string should now be used instead
2
3use super::{Decode, DecodeError, Encode, EncodeError};
4
5impl Encode for String {
6    fn encode<W: bytes::BufMut>(&self, w: &mut W) -> Result<(), EncodeError> {
7        self.len().encode(w)?;
8        Self::encode_remaining(w, self.len())?;
9        w.put(self.as_ref());
10        Ok(())
11    }
12}
13
14impl Decode for String {
15    /// Decode a string with a varint length prefix.
16    fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
17        let size = usize::decode(r)?;
18
19        Self::decode_remaining(r, size)?;
20
21        let mut buf = vec![0; size];
22        r.copy_to_slice(&mut buf);
23        let str = String::from_utf8(buf)?;
24
25        Ok(str)
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use bytes::BytesMut;
33
34    #[test]
35    fn encode_decode() {
36        let mut buf = BytesMut::new();
37
38        let s = "teststring".to_string();
39        s.encode(&mut buf).unwrap();
40        assert_eq!(
41            buf.to_vec(),
42            vec![
43                0x0a, // Length of "teststring" is 10
44                0x74, 0x65, 0x73, 0x74, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67
45            ]
46        );
47        let decoded = String::decode(&mut buf).unwrap();
48        assert_eq!(decoded, s);
49    }
50}