messagepack_core/decode/
str.rs

1use super::{Decode, Error, NbyteReader, Result};
2use crate::formats::Format;
3
4pub struct StrDecoder;
5
6impl<'a> Decode<'a> for StrDecoder {
7    type Value = &'a str;
8    fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
9        let (format, buf) = Format::decode(buf)?;
10        match format {
11            Format::FixStr(_) | Format::Str8 | Format::Str16 | Format::Str32 => {
12                Self::decode_with_format(format, buf)
13            }
14            _ => Err(Error::UnexpectedFormat),
15        }
16    }
17
18    fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
19        let (len, buf) = match format {
20            Format::FixStr(n) => (n.into(), buf),
21            Format::Str8 => NbyteReader::<1>::read(buf)?,
22            Format::Str16 => NbyteReader::<2>::read(buf)?,
23            Format::Str32 => NbyteReader::<4>::read(buf)?,
24            _ => return Err(Error::UnexpectedFormat),
25        };
26        let (data, rest) = buf.split_at_checked(len).ok_or(Error::EofData)?;
27        let s = core::str::from_utf8(data).map_err(|_| Error::InvalidData)?;
28        Ok((s, rest))
29    }
30}
31
32impl<'a> Decode<'a> for &'a str {
33    type Value = &'a str;
34
35    fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
36        StrDecoder::decode(buf)
37    }
38
39    fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
40        StrDecoder::decode_with_format(format, buf)
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn decode_str() {
50        let buf: &[u8] = &[
51            0xab, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64,
52        ];
53
54        let (decoded, rest) = StrDecoder::decode(buf).unwrap();
55        let expect = "Hello World";
56        assert_eq!(decoded, expect);
57        assert_eq!(rest.len(), 0);
58    }
59
60    #[test]
61    fn decode_invalid_str() {
62        let buf: &[u8] = &[0xa2, 0xc3, 0x28];
63        let err = StrDecoder::decode(buf).unwrap_err();
64        assert_eq!(err, Error::InvalidData);
65
66        let buf: &[u8] = &[0xa1, 0x80];
67        let err = StrDecoder::decode(buf).unwrap_err();
68        assert_eq!(err, Error::InvalidData);
69    }
70}