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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! Contains extensions of `serde` and internal reexports.

#[doc(hidden)]
pub use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};

/// Converts given error type to a type implementing [`de::Error`].
///
/// This is used in [`Deserialize`] implementations to convert specialized errors into serde
/// errors.
pub trait IntoDeError: Sized {
    /// Converts to deserializer error possibly outputting vague message.
    ///
    /// This method is allowed to return a vague error message if the error type doesn't contain
    /// enough information to explain the error precisely.
    fn into_de_error<E: de::Error>(self, expected: Option<&dyn de::Expected>) -> E;

    /// Converts to deserializer error without outputting vague message.
    ///
    /// If the error type doesn't contain enough information to explain the error precisely this
    /// should return `Err(self)` allowing the caller to use its information instead.
    fn try_into_de_error<E>(self, expected: Option<&dyn de::Expected>) -> Result<E, Self>
    where
        E: de::Error,
    {
        Ok(self.into_de_error(expected))
    }
}

mod impls {
    use super::*;

    impl IntoDeError for core::convert::Infallible {
        fn into_de_error<E: de::Error>(self, _expected: Option<&dyn de::Expected>) -> E {
            match self {}
        }
    }

    impl IntoDeError for core::num::ParseIntError {
        fn into_de_error<E: de::Error>(self, expected: Option<&dyn de::Expected>) -> E {
            self.try_into_de_error(expected).unwrap_or_else(|_| {
                let expected = expected.unwrap_or(&"an integer");

                E::custom(format_args!("invalid string, expected {}", expected))
            })
        }

        fn try_into_de_error<E>(self, expected: Option<&dyn de::Expected>) -> Result<E, Self>
        where
            E: de::Error,
        {
            use core::num::IntErrorKind::Empty;

            let expected = expected.unwrap_or(&"an integer");

            match self.kind() {
                Empty => Ok(E::invalid_value(de::Unexpected::Str(""), expected)),
                _ => Err(self),
            }
        }
    }
}

/// Implements `serde::Serialize` by way of `Display`.
///
/// `$name` is required to implement `core::fmt::Display`.
#[macro_export]
macro_rules! serde_string_serialize_impl {
    ($name:ty, $expecting:literal) => {
        impl $crate::serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
            where
                S: $crate::serde::Serializer,
            {
                serializer.collect_str(&self)
            }
        }
    };
}

/// Implements `serde::Deserialize` by way of `FromStr`.
///
/// `$name` is required to implement `core::str::FromStr`.
#[macro_export]
macro_rules! serde_string_deserialize_impl {
    ($name:ty, $expecting:literal) => {
        impl<'de> $crate::serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> core::result::Result<$name, D::Error>
            where
                D: $crate::serde::de::Deserializer<'de>,
            {
                use core::fmt::Formatter;

                struct Visitor;
                impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
                    type Value = $name;

                    fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
                        f.write_str($expecting)
                    }

                    fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
                    where
                        E: $crate::serde::de::Error,
                    {
                        v.parse::<$name>().map_err(E::custom)
                    }
                }

                deserializer.deserialize_str(Visitor)
            }
        }
    };
}

/// Implements `serde::Serialize` and `Deserialize` by way of `Display` and `FromStr` respectively.
///
/// `$name` is required to implement `core::fmt::Display` and `core::str::FromStr`.
#[macro_export]
macro_rules! serde_string_impl {
    ($name:ty, $expecting:literal) => {
        $crate::serde_string_deserialize_impl!($name, $expecting);
        $crate::serde_string_serialize_impl!($name, $expecting);
    };
}

/// A combination macro where the human-readable serialization is done like
/// serde_string_impl and the non-human-readable impl is done as a struct.
#[macro_export]
macro_rules! serde_struct_human_string_impl {
    ($name:ident, $expecting:literal, $($fe:ident),*) => (
        impl<'de> $crate::serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> core::result::Result<$name, D::Error>
            where
                D: $crate::serde::de::Deserializer<'de>,
            {
                if deserializer.is_human_readable() {
                    use core::fmt::Formatter;

                    struct Visitor;
                    impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
                        type Value = $name;

                        fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
                            f.write_str($expecting)
                        }

                        fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
                        where
                            E: $crate::serde::de::Error,
                        {
                            v.parse::<$name>().map_err(E::custom)
                        }

                    }

                    deserializer.deserialize_str(Visitor)
                } else {
                    use core::fmt::Formatter;
                    use $crate::serde::de::IgnoredAny;

                    #[allow(non_camel_case_types)]
                    enum Enum { Unknown__Field, $($fe),* }

                    struct EnumVisitor;
                    impl<'de> $crate::serde::de::Visitor<'de> for EnumVisitor {
                        type Value = Enum;

                        fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
                            f.write_str("a field name")
                        }

                        fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
                        where
                            E: $crate::serde::de::Error,
                        {
                            match v {
                                $(
                                stringify!($fe) => Ok(Enum::$fe)
                                ),*,
                                _ => Ok(Enum::Unknown__Field)
                            }
                        }
                    }

                    impl<'de> $crate::serde::Deserialize<'de> for Enum {
                        fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
                        where
                            D: $crate::serde::de::Deserializer<'de>,
                        {
                            deserializer.deserialize_str(EnumVisitor)
                        }
                    }

                    struct Visitor;

                    impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
                        type Value = $name;

                        fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
                            f.write_str("a struct")
                        }

                        fn visit_seq<V>(self, mut seq: V) -> core::result::Result<Self::Value, V::Error>
                        where
                            V: $crate::serde::de::SeqAccess<'de>,
                        {
                            use $crate::serde::de::Error;

                            let length = 0;
                            $(
                                let $fe = seq.next_element()?.ok_or_else(|| {
                                    Error::invalid_length(length, &self)
                                })?;
                                #[allow(unused_variables)]
                                let length = length + 1;
                            )*

                            let ret = $name {
                                $($fe),*
                            };

                            Ok(ret)
                        }

                        fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
                        where
                            A: $crate::serde::de::MapAccess<'de>,
                        {
                            use $crate::serde::de::Error;

                            $(let mut $fe = None;)*

                            loop {
                                match map.next_key::<Enum>()? {
                                    Some(Enum::Unknown__Field) => {
                                        map.next_value::<IgnoredAny>()?;
                                    }
                                    $(
                                        Some(Enum::$fe) => {
                                            $fe = Some(map.next_value()?);
                                        }
                                    )*
                                    None => { break; }
                                }
                            }

                            $(
                                let $fe = match $fe {
                                    Some(x) => x,
                                    None => return Err(A::Error::missing_field(stringify!($fe))),
                                };
                            )*

                            let ret = $name {
                                $($fe),*
                            };

                            Ok(ret)
                        }
                    }
                    // end type defs

                    static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*];

                    deserializer.deserialize_struct(stringify!($name), FIELDS, Visitor)
                }
            }
        }

        impl $crate::serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
            where
                S: $crate::serde::Serializer,
            {
                if serializer.is_human_readable() {
                    serializer.collect_str(&self)
                } else {
                    use $crate::serde::ser::SerializeStruct;

                    // Only used to get the struct length.
                    static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*];

                    let mut st = serializer.serialize_struct(stringify!($name), FIELDS.len())?;

                    $(
                        st.serialize_field(stringify!($fe), &self.$fe)?;
                    )*

                    st.end()
                }
            }
        }
    )
}

/// Does round trip test to/from serde value.
#[cfg(feature = "test-serde")]
#[macro_export]
macro_rules! serde_round_trip (
    ($var:expr) => ({
        use serde_json;

        let encoded = $crate::serde_json::to_value(&$var).expect("serde_json failed to encode");
        let decoded = $crate::serde_json::from_value(encoded).expect("serde_json failed to decode");
        assert_eq!($var, decoded);

        let encoded = $crate::bincode::serialize(&$var).expect("bincode failed to encode");
        let decoded = $crate::bincode::deserialize(&encoded).expect("bincode failed to decode");
        assert_eq!($var, decoded);
    })
);