messagepack_core/decode/
bin.rs1use super::{Decode, Error, NbyteReader, Result};
2use crate::formats::Format;
3
4pub struct BinDecoder;
5
6impl<'a> Decode<'a> for BinDecoder {
7 type Value = &'a [u8];
8 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
9 let (format, buf) = Format::decode(buf)?;
10 match format {
11 Format::Bin8 | Format::Bin16 | Format::Bin32 => Self::decode_with_format(format, buf),
12 _ => Err(Error::UnexpectedFormat),
13 }
14 }
15 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
16 let (len, buf) = match format {
17 Format::Bin8 => NbyteReader::<1>::read(buf)?,
18 Format::Bin16 => NbyteReader::<2>::read(buf)?,
19 Format::Bin32 => NbyteReader::<4>::read(buf)?,
20 _ => return Err(Error::UnexpectedFormat),
21 };
22 let (data, rest) = buf.split_at_checked(len).ok_or(Error::EofData)?;
23 Ok((data, rest))
24 }
25}
26
27impl<'a> Decode<'a> for &'a [u8] {
28 type Value = &'a [u8];
29 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
30 BinDecoder::decode(buf)
31 }
32 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
33 BinDecoder::decode_with_format(format, buf)
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40 #[test]
41 fn decode_bin8() {
42 let expect = r#"
43MessagePack
44"#
45 .as_bytes();
46 let len = u8::try_from(expect.len()).unwrap();
47 let buf = [0xc4_u8]
48 .into_iter()
49 .chain(len.to_be_bytes())
50 .chain(expect.iter().cloned())
51 .collect::<Vec<_>>();
52
53 let (decoded, rest) = BinDecoder::decode(&buf).unwrap();
54 assert_eq!(decoded, expect);
55 assert_eq!(rest.len(), 0);
56 }
57
58 #[test]
59 fn decode_bin16() {
60 let expect = r#"
61MessagePack is an object serialization specification like JSON.
62
63MessagePack has two concepts: type system and formats.
64
65Serialization is conversion from application objects into MessagePack formats via MessagePack type system.
66
67Deserialization is conversion from MessagePack formats into application objects via MessagePack type system.
68"#.as_bytes();
69 let len = u16::try_from(expect.len()).unwrap();
70 let buf = [0xc5_u8]
71 .into_iter()
72 .chain(len.to_be_bytes())
73 .chain(expect.iter().cloned())
74 .collect::<Vec<_>>();
75
76 let (decoded, rest) = BinDecoder::decode(&buf).unwrap();
77 assert_eq!(decoded, expect);
78 assert_eq!(rest.len(), 0);
79 }
80
81 #[test]
82 fn decode_bin32() {
83 let expect = include_str!("bin.rs").as_bytes();
84 let len = u32::try_from(expect.len()).unwrap();
85 let buf = [0xc6_u8]
86 .into_iter()
87 .chain(len.to_be_bytes())
88 .chain(expect.iter().cloned())
89 .collect::<Vec<_>>();
90
91 let (decoded, rest) = BinDecoder::decode(&buf).unwrap();
92 assert_eq!(decoded, expect);
93 assert_eq!(rest.len(), 0);
94 }
95}