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 serde::ser::Error for Box<Error> {
70 fn custom<T>(msg: T) -> Self
71 where
72 T: fmt::Display,
73 {
74 Box::new(Error::Custom(msg.to_string()))
75 }
76}
77
78impl serde::de::Error for Box<Error> {
79 fn custom<T>(msg: T) -> Self
80 where
81 T: fmt::Display,
82 {
83 Box::new(Error::Custom(msg.to_string()))
84 }
85}