messagepack_serde/ser/
error.rs1use serde::ser;
2
3pub(crate) type CoreError<T> = messagepack_core::encode::Error<T>;
4
5#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
7pub enum Error<T> {
8 Encode(CoreError<T>),
10 SeqLenNone,
12 #[cfg(not(feature = "alloc"))]
13 Custom,
15 #[cfg(feature = "alloc")]
16 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)]
68pub(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}