mls_rs_codec/
string.rs

1use crate::{MlsDecode, MlsEncode, MlsSize};
2use alloc::{string::String, vec::Vec};
3
4impl MlsSize for str {
5    fn mls_encoded_len(&self) -> usize {
6        self.as_bytes().mls_encoded_len()
7    }
8}
9
10impl MlsEncode for str {
11    fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
12        self.as_bytes().mls_encode(writer)
13    }
14}
15
16impl MlsSize for String {
17    fn mls_encoded_len(&self) -> usize {
18        self.as_str().mls_encoded_len()
19    }
20}
21
22impl MlsEncode for String {
23    fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), crate::Error> {
24        self.as_str().mls_encode(writer)
25    }
26}
27
28impl MlsDecode for String {
29    fn mls_decode(reader: &mut &[u8]) -> Result<Self, crate::Error> {
30        String::from_utf8(Vec::mls_decode(reader)?).map_err(|_| crate::Error::Utf8)
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use crate::{Error, MlsDecode, MlsEncode};
37    use alloc::string::String;
38    use assert_matches::assert_matches;
39
40    #[cfg(target_arch = "wasm32")]
41    use wasm_bindgen_test::wasm_bindgen_test as test;
42
43    #[test]
44    fn serialization_works() {
45        assert_eq!(
46            vec![3, b'b', b'a', b'r'],
47            "bar".mls_encode_to_vec().unwrap()
48        );
49    }
50
51    #[test]
52    fn data_round_trips() {
53        let val = "foo";
54        let x = val.mls_encode_to_vec().unwrap();
55        assert_eq!(val, String::mls_decode(&mut &*x).unwrap());
56    }
57
58    #[test]
59    fn empty_string_can_be_deserialized() {
60        assert_eq!(String::new(), String::mls_decode(&mut &[0u8][..]).unwrap());
61    }
62
63    #[test]
64    fn too_short_string_to_deserialize_gives_an_error() {
65        assert_matches!(
66            String::mls_decode(&mut &[2, 3][..]),
67            Err(Error::UnexpectedEOF)
68        );
69    }
70
71    #[test]
72    fn deserializing_invalid_utf8_fails() {
73        assert_matches!(
74            String::mls_decode(&mut &[0x02, 0xdf, 0xff][..]),
75            Err(Error::Utf8)
76        );
77    }
78}