messagepack_core/decode/
mod.rs1use crate::Format;
2
3mod array;
4pub use array::ArrayDecoder;
5mod bin;
6pub use bin::BinDecoder;
7mod bool;
8mod extension;
9pub use extension::{Extension, ExtensionDecoder};
10mod float;
11mod int;
12mod map;
13pub use map::MapDecoder;
14mod nil;
15pub use nil::NilDecoder;
16mod str;
17pub use str::StrDecoder;
18
19#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
21pub enum Error {
22 InvalidData,
24 UnexpectedFormat,
26 EofFormat,
28 EofData,
30}
31
32impl core::fmt::Display for Error {
33 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34 match self {
35 Error::InvalidData => write!(f, "Cannot decode invalid data"),
36 Error::UnexpectedFormat => write!(f, "Unexpected format found"),
37 Error::EofFormat => write!(f, "EOF while parse format"),
38 Error::EofData => write!(f, "EOF while parse data"),
39 }
40 }
41}
42
43impl core::error::Error for Error {}
44
45type Result<T> = ::core::result::Result<T, Error>;
46
47pub trait Decode<'a> {
48 type Value: Sized;
49 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])>;
51
52 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])>;
54}
55
56impl<'a> Decode<'a> for Format {
57 type Value = Self;
58 fn decode(buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
59 let (first, rest) = buf.split_first().ok_or(Error::EofFormat)?;
60
61 Ok((Self::from_byte(*first), rest))
62 }
63
64 fn decode_with_format(format: Format, buf: &'a [u8]) -> Result<(Self::Value, &'a [u8])> {
65 let _ = (format, buf);
66 unreachable!()
67 }
68}
69
70pub struct NbyteReader<const NBYTE: usize>;
71
72macro_rules! impl_read {
73 ($ty:ty) => {
74 pub fn read(buf: &[u8]) -> Result<(usize, &[u8])> {
75 const SIZE: usize = core::mem::size_of::<$ty>();
76 let (data, rest) = buf.split_at_checked(SIZE).ok_or(Error::EofData)?;
77 let data: [u8; SIZE] = data.try_into().map_err(|_| Error::EofData)?;
78 let val =
79 usize::try_from(<$ty>::from_be_bytes(data)).map_err(|_| Error::InvalidData)?;
80 Ok((val, rest))
81 }
82 };
83}
84
85impl NbyteReader<1> {
86 impl_read! {u8}
87}
88
89impl NbyteReader<2> {
90 impl_read! {u16}
91}
92impl NbyteReader<4> {
93 impl_read! {u32}
94}