1use core::fmt;
2
3use musli::Context;
4
5#[cfg(feature = "alloc")]
6use alloc::boxed::Box;
7#[cfg(feature = "alloc")]
8use alloc::format;
9
10#[derive(Debug)]
11pub enum SerdeError {
12 Captured,
13 #[cfg(not(feature = "alloc"))]
14 Custom,
15 #[cfg(feature = "alloc")]
16 Custom(Box<str>),
17}
18
19impl SerdeError {
20 pub(super) fn report<C: ?Sized + Context>(self, cx: &C) -> Option<C::Error> {
21 match self {
22 SerdeError::Captured => None,
23 #[cfg(not(feature = "alloc"))]
24 SerdeError::Custom => {
25 Some(cx.message("Error in musli-serde (enable alloc for details)"))
26 }
27 #[cfg(feature = "alloc")]
28 SerdeError::Custom(message) => Some(cx.message(message)),
29 }
30 }
31}
32
33impl fmt::Display for SerdeError {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 write!(f, "Error in musli-serde")
36 }
37}
38
39impl serde::ser::Error for SerdeError {
40 #[cfg(feature = "alloc")]
41 fn custom<T>(msg: T) -> Self
42 where
43 T: fmt::Display,
44 {
45 SerdeError::Custom(format!("{}", msg).into())
46 }
47
48 #[cfg(not(feature = "alloc"))]
49 fn custom<T>(_: T) -> Self
50 where
51 T: fmt::Display,
52 {
53 SerdeError::Custom
54 }
55}
56
57impl serde::de::Error for SerdeError {
58 #[cfg(feature = "alloc")]
59 fn custom<T>(msg: T) -> Self
60 where
61 T: fmt::Display,
62 {
63 SerdeError::Custom(format!("{}", msg).into())
64 }
65
66 #[cfg(not(feature = "alloc"))]
67 fn custom<T>(_: T) -> Self
68 where
69 T: fmt::Display,
70 {
71 SerdeError::Custom
72 }
73}
74
75impl serde::de::StdError for SerdeError {}