1use crate::alloc_prelude::*;
2
3#[derive(Clone, PartialEq, Eq)]
5pub struct Error {
6 pub(crate) inner: ErrorInner,
7}
8
9impl Error {
10 pub(crate) fn new(inner: impl core::fmt::Display) -> Self {
11 Self {
12 inner: ErrorInner::Custom(inner.to_string()),
13 }
14 }
15
16 pub(crate) fn unsupported_type(t: Option<&'static str>) -> Self {
17 Self {
18 inner: ErrorInner::UnsupportedType(t),
19 }
20 }
21
22 pub(crate) fn unsupported_none() -> Self {
23 Self {
24 inner: ErrorInner::UnsupportedNone,
25 }
26 }
27
28 pub(crate) fn key_not_string() -> Self {
29 Self {
30 inner: ErrorInner::KeyNotString,
31 }
32 }
33
34 #[cfg(feature = "display")]
35 pub(crate) fn date_invalid() -> Self {
36 Self {
37 inner: ErrorInner::DateInvalid,
38 }
39 }
40}
41
42impl From<core::fmt::Error> for Error {
43 fn from(_: core::fmt::Error) -> Self {
44 Self::new("an error occurred when writing a value")
45 }
46}
47
48impl serde_core::ser::Error for Error {
49 fn custom<T>(msg: T) -> Self
50 where
51 T: core::fmt::Display,
52 {
53 Self::new(msg)
54 }
55}
56
57impl core::fmt::Display for Error {
58 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59 self.inner.fmt(f)
60 }
61}
62
63impl core::fmt::Debug for Error {
64 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
65 self.inner.fmt(f)
66 }
67}
68
69#[cfg(feature = "std")]
70impl std::error::Error for Error {}
71#[cfg(not(feature = "std"))]
72impl serde_core::de::StdError for Error {}
73
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub(crate) enum ErrorInner {
78 UnsupportedType(Option<&'static str>),
80 UnsupportedNone,
82 KeyNotString,
84 DateInvalid,
86 Custom(String),
88}
89
90impl core::fmt::Display for ErrorInner {
91 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92 match self {
93 Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
94 Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
95 Self::UnsupportedNone => "unsupported None value".fmt(formatter),
96 Self::KeyNotString => "map key was not a string".fmt(formatter),
97 Self::DateInvalid => "a serialized date was invalid".fmt(formatter),
98 Self::Custom(s) => s.fmt(formatter),
99 }
100 }
101}