Skip to main content

messagepack_serde/ser/
error.rs

1use serde::ser;
2
3pub(crate) type CoreError<T> = messagepack_core::encode::Error<T>;
4
5/// Error during serialization
6#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
7pub enum Error<T> {
8    /// Core error
9    Encode(CoreError<T>),
10    /// Tried to serialize an array or map without a length while `alloc` is disabled.
11    SeqLenNone,
12    #[cfg(not(feature = "alloc"))]
13    /// Custom serialization error.
14    Custom,
15    #[cfg(feature = "alloc")]
16    /// Custom serialization error.
17    Custom(alloc::string::String),
18}
19
20impl<T: core::fmt::Display> core::fmt::Display for Error<T> {
21    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22        match self {
23            Error::Encode(e) => e.fmt(f),
24            #[cfg(not(feature = "alloc"))]
25            Error::Custom => write!(f, "unknown error"),
26            #[cfg(feature = "alloc")]
27            Error::Custom(msg) => f.write_str(msg),
28            Error::SeqLenNone => {
29                write!(
30                    f,
31                    "array/map family must be provided length when `alloc` feature is disabled"
32                )
33            }
34        }
35    }
36}
37
38impl<T> From<CoreError<T>> for Error<T> {
39    fn from(err: CoreError<T>) -> Self {
40        Error::Encode(err)
41    }
42}
43
44impl<T> ser::StdError for Error<T> where T: core::error::Error {}
45impl<E> ser::Error for Error<E>
46where
47    E: core::error::Error,
48{
49    #[allow(unused_variables)]
50    fn custom<T>(msg: T) -> Self
51    where
52        T: core::fmt::Display,
53    {
54        #[cfg(not(feature = "alloc"))]
55        {
56            Self::Custom
57        }
58
59        #[cfg(feature = "alloc")]
60        {
61            use alloc::string::ToString;
62            Self::Custom(msg.to_string())
63        }
64    }
65}
66
67#[allow(unused)]
68/// Convert `Error<Infallible>` to `crate::ser::Error<T>`
69/// This is used when `alloc` feature enabled
70pub(crate) fn convert_error<T>(err: Error<core::convert::Infallible>) -> Error<T> {
71    match err {
72        Error::Encode(e) => match e {
73            messagepack_core::encode::Error::Io(_e) => {
74                unreachable!("infallible error should never occur")
75            }
76            messagepack_core::encode::Error::InvalidFormat => {
77                messagepack_core::encode::Error::InvalidFormat.into()
78            }
79        },
80        Error::SeqLenNone => Error::SeqLenNone,
81        #[cfg(not(feature = "alloc"))]
82        Error::Custom => Error::Custom,
83        #[cfg(feature = "alloc")]
84        Error::Custom(msg) => Error::Custom(msg),
85    }
86}