serde_mincode/
lib.rs

1mod de;
2mod ser;
3
4use std::error::Error as StdError;
5use std::fmt;
6use std::marker::PhantomData;
7
8use de::Decoder;
9use ser::Encoder;
10
11pub fn serialize<T>(value: &T) -> Result<Vec<u8>, Box<Error>>
12where
13    T: serde::ser::Serialize,
14{
15    let mut buf = Vec::new();
16    serialize_into(&mut buf, value)?;
17    Ok(buf)
18}
19
20pub fn serialize_into<T>(buf: &mut Vec<u8>, value: &T) -> Result<(), Box<Error>>
21where
22    T: serde::ser::Serialize,
23{
24    value.serialize(Encoder::new(buf))?;
25    Ok(())
26}
27
28pub fn deserialize<'de, T>(buf: &'de [u8]) -> Result<T, Box<Error>>
29where
30    T: serde::de::Deserialize<'de>,
31{
32    deserialize_seed(buf, PhantomData)
33}
34
35pub fn deserialize_seed<'de, T>(buf: &'de [u8], seed: T) -> Result<T::Value, Box<Error>>
36where
37    T: serde::de::DeserializeSeed<'de>,
38{
39    seed.deserialize(&mut Decoder::new(buf))
40}
41
42#[derive(Debug)]
43pub enum Error {
44    MissingData,
45    NotSupported,
46    InvalidBool,
47    InvalidChar,
48    InvalidStr,
49    InvalidOption,
50    Custom(String),
51}
52
53impl fmt::Display for Error {
54    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::MissingData => fmt.write_str("missing data"),
57            Self::NotSupported => fmt.write_str("not supported"),
58            Self::InvalidBool => fmt.write_str("invalid bool"),
59            Self::InvalidChar => fmt.write_str("invalid char"),
60            Self::InvalidStr => fmt.write_str("invalid str"),
61            Self::InvalidOption => fmt.write_str("invalid option"),
62            Self::Custom(msg) => write!(fmt, "custom: {msg}"),
63        }
64    }
65}
66
67impl StdError for Error {}
68
69impl<T> From<Error> for Result<T, Box<Error>> {
70    #[cold]
71    fn from(err: Error) -> Self {
72        Err(Box::new(err))
73    }
74}
75
76impl serde::ser::Error for Box<Error> {
77    #[cold]
78    fn custom<T>(msg: T) -> Self
79    where
80        T: fmt::Display,
81    {
82        Box::new(Error::Custom(msg.to_string()))
83    }
84}
85
86impl serde::de::Error for Box<Error> {
87    #[cold]
88    fn custom<T>(msg: T) -> Self
89    where
90        T: fmt::Display,
91    {
92        Box::new(Error::Custom(msg.to_string()))
93    }
94}