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