1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt::{self, Debug, Display};
use serde::de::Expected;

/// Error when a `Serializer` or `Deserializer` trait object fails.
pub struct Error {
    imp: Box<ErrorImpl>,
}

/// Result type alias where the error is `erased_serde::Error`.
pub type Result<T> = core::result::Result<T, Error>;

pub(crate) fn erase_de<E: serde::de::Error>(e: E) -> Error {
    serde::de::Error::custom(e)
}

pub(crate) fn unerase_de<E: serde::de::Error>(e: Error) -> E {
    e.as_serde_de_error()
}

impl Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let error = self.as_serde_de_error::<serde::de::value::Error>();
        Display::fmt(&error, formatter)
    }
}

impl Debug for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let error = self.as_serde_de_error::<serde::de::value::Error>();
        Debug::fmt(&error, formatter)
    }
}

impl serde::ser::StdError for Error {}

enum ErrorImpl {
    Custom(String),
    InvalidType {
        unexpected: Unexpected,
        expected: String,
    },
    InvalidValue {
        unexpected: Unexpected,
        expected: String,
    },
    InvalidLength {
        len: usize,
        expected: String,
    },
    UnknownVariant {
        variant: String,
        expected: &'static [&'static str],
    },
    UnknownField {
        field: String,
        expected: &'static [&'static str],
    },
    MissingField {
        field: &'static str,
    },
    DuplicateField {
        field: &'static str,
    },
}

enum Unexpected {
    Bool(bool),
    Unsigned(u64),
    Signed(i64),
    Float(f64),
    Char(char),
    Str(String),
    Bytes(Vec<u8>),
    Unit,
    Option,
    NewtypeStruct,
    Seq,
    Map,
    Enum,
    UnitVariant,
    NewtypeVariant,
    TupleVariant,
    StructVariant,
    Other(String),
}

impl serde::ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        let imp = Box::new(ErrorImpl::Custom(msg.to_string()));
        Error { imp }
    }
}

impl serde::de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        let imp = Box::new(ErrorImpl::Custom(msg.to_string()));
        Error { imp }
    }

    fn invalid_type(unexpected: serde::de::Unexpected, expected: &dyn Expected) -> Self {
        let imp = Box::new(ErrorImpl::InvalidType {
            unexpected: Unexpected::from_serde(unexpected),
            expected: expected.to_string(),
        });
        Error { imp }
    }

    fn invalid_value(unexpected: serde::de::Unexpected, expected: &dyn Expected) -> Self {
        let imp = Box::new(ErrorImpl::InvalidValue {
            unexpected: Unexpected::from_serde(unexpected),
            expected: expected.to_string(),
        });
        Error { imp }
    }

    fn invalid_length(len: usize, expected: &dyn Expected) -> Self {
        let imp = Box::new(ErrorImpl::InvalidLength {
            len,
            expected: expected.to_string(),
        });
        Error { imp }
    }

    fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
        let imp = Box::new(ErrorImpl::UnknownVariant {
            variant: variant.to_owned(),
            expected,
        });
        Error { imp }
    }

    fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
        let imp = Box::new(ErrorImpl::UnknownField {
            field: field.to_owned(),
            expected,
        });
        Error { imp }
    }

    fn missing_field(field: &'static str) -> Self {
        let imp = Box::new(ErrorImpl::MissingField { field });
        Error { imp }
    }

    fn duplicate_field(field: &'static str) -> Self {
        let imp = Box::new(ErrorImpl::DuplicateField { field });
        Error { imp }
    }
}

impl Error {
    fn as_serde_de_error<E: serde::de::Error>(&self) -> E {
        match self.imp.as_ref() {
            ErrorImpl::Custom(msg) => E::custom(msg),
            ErrorImpl::InvalidType {
                unexpected,
                expected,
            } => E::invalid_type(unexpected.as_serde(), &expected.as_str()),
            ErrorImpl::InvalidValue {
                unexpected,
                expected,
            } => E::invalid_value(unexpected.as_serde(), &expected.as_str()),
            ErrorImpl::InvalidLength { len, expected } => {
                E::invalid_length(*len, &expected.as_str())
            }
            ErrorImpl::UnknownVariant { variant, expected } => {
                E::unknown_variant(variant, expected)
            }
            ErrorImpl::UnknownField { field, expected } => E::unknown_field(field, expected),
            ErrorImpl::MissingField { field } => E::missing_field(field),
            ErrorImpl::DuplicateField { field } => E::duplicate_field(field),
        }
    }
}

impl Unexpected {
    fn from_serde(unexpected: serde::de::Unexpected) -> Self {
        match unexpected {
            serde::de::Unexpected::Bool(value) => Unexpected::Bool(value),
            serde::de::Unexpected::Unsigned(value) => Unexpected::Unsigned(value),
            serde::de::Unexpected::Signed(value) => Unexpected::Signed(value),
            serde::de::Unexpected::Float(value) => Unexpected::Float(value),
            serde::de::Unexpected::Char(value) => Unexpected::Char(value),
            serde::de::Unexpected::Str(value) => Unexpected::Str(value.to_owned()),
            serde::de::Unexpected::Bytes(value) => Unexpected::Bytes(value.to_owned()),
            serde::de::Unexpected::Unit => Unexpected::Unit,
            serde::de::Unexpected::Option => Unexpected::Option,
            serde::de::Unexpected::NewtypeStruct => Unexpected::NewtypeStruct,
            serde::de::Unexpected::Seq => Unexpected::Seq,
            serde::de::Unexpected::Map => Unexpected::Map,
            serde::de::Unexpected::Enum => Unexpected::Enum,
            serde::de::Unexpected::UnitVariant => Unexpected::UnitVariant,
            serde::de::Unexpected::NewtypeVariant => Unexpected::NewtypeVariant,
            serde::de::Unexpected::TupleVariant => Unexpected::TupleVariant,
            serde::de::Unexpected::StructVariant => Unexpected::StructVariant,
            serde::de::Unexpected::Other(msg) => Unexpected::Other(msg.to_owned()),
        }
    }

    fn as_serde(&self) -> serde::de::Unexpected {
        match self {
            Unexpected::Bool(value) => serde::de::Unexpected::Bool(*value),
            Unexpected::Unsigned(value) => serde::de::Unexpected::Unsigned(*value),
            Unexpected::Signed(value) => serde::de::Unexpected::Signed(*value),
            Unexpected::Float(value) => serde::de::Unexpected::Float(*value),
            Unexpected::Char(value) => serde::de::Unexpected::Char(*value),
            Unexpected::Str(value) => serde::de::Unexpected::Str(value),
            Unexpected::Bytes(value) => serde::de::Unexpected::Bytes(value),
            Unexpected::Unit => serde::de::Unexpected::Unit,
            Unexpected::Option => serde::de::Unexpected::Option,
            Unexpected::NewtypeStruct => serde::de::Unexpected::NewtypeStruct,
            Unexpected::Seq => serde::de::Unexpected::Seq,
            Unexpected::Map => serde::de::Unexpected::Map,
            Unexpected::Enum => serde::de::Unexpected::Enum,
            Unexpected::UnitVariant => serde::de::Unexpected::UnitVariant,
            Unexpected::NewtypeVariant => serde::de::Unexpected::NewtypeVariant,
            Unexpected::TupleVariant => serde::de::Unexpected::TupleVariant,
            Unexpected::StructVariant => serde::de::Unexpected::StructVariant,
            Unexpected::Other(msg) => serde::de::Unexpected::Other(msg),
        }
    }
}