bitcoin_internals/
serde.rs

1//! Contains extensions of `serde` and internal reexports.
2
3#[doc(hidden)]
4pub use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};
5
6/// Converts given error type to a type implementing [`de::Error`].
7///
8/// This is used in [`Deserialize`] implementations to convert specialized errors into serde
9/// errors.
10pub trait IntoDeError: Sized {
11    /// Converts to deserializer error possibly outputting vague message.
12    ///
13    /// This method is allowed to return a vague error message if the error type doesn't contain
14    /// enough information to explain the error precisely.
15    fn into_de_error<E: de::Error>(self, expected: Option<&dyn de::Expected>) -> E;
16
17    /// Converts to deserializer error without outputting vague message.
18    ///
19    /// If the error type doesn't contain enough information to explain the error precisely this
20    /// should return `Err(self)` allowing the caller to use its information instead.
21    ///
22    /// # Errors
23    ///
24    /// Returns `Err(self)` if the error cannot be converted to a deserializer error.
25    fn try_into_de_error<E>(self, expected: Option<&dyn de::Expected>) -> Result<E, Self>
26    where
27        E: de::Error,
28    {
29        Ok(self.into_de_error(expected))
30    }
31}
32
33mod impls {
34    use super::{de, IntoDeError};
35
36    impl IntoDeError for core::convert::Infallible {
37        fn into_de_error<E: de::Error>(self, _expected: Option<&dyn de::Expected>) -> E {
38            match self {}
39        }
40    }
41
42    impl IntoDeError for core::num::ParseIntError {
43        fn into_de_error<E: de::Error>(self, expected: Option<&dyn de::Expected>) -> E {
44            self.try_into_de_error(expected).unwrap_or_else(|_| {
45                let expected = expected.unwrap_or(&"an integer");
46
47                E::custom(format_args!("invalid string, expected {}", expected))
48            })
49        }
50
51        fn try_into_de_error<E>(self, expected: Option<&dyn de::Expected>) -> Result<E, Self>
52        where
53            E: de::Error,
54        {
55            use core::num::IntErrorKind::Empty;
56
57            let expected = expected.unwrap_or(&"an integer");
58
59            match self.kind() {
60                Empty => Ok(E::invalid_value(de::Unexpected::Str(""), expected)),
61                _ => Err(self),
62            }
63        }
64    }
65}
66
67/// Implements `serde::Serialize` by way of `Display`.
68///
69/// `$name` is required to implement `core::fmt::Display`.
70#[macro_export]
71macro_rules! serde_string_serialize_impl {
72    ($name:ty, $expecting:literal) => {
73        impl $crate::serde::Serialize for $name {
74            fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
75            where
76                S: $crate::serde::Serializer,
77            {
78                serializer.collect_str(&self)
79            }
80        }
81    };
82}
83
84/// Implements `serde::Deserialize` by way of `FromStr`.
85///
86/// `$name` is required to implement `core::str::FromStr`.
87#[macro_export]
88macro_rules! serde_string_deserialize_impl {
89    ($name:ty, $expecting:literal) => {
90        impl<'de> $crate::serde::Deserialize<'de> for $name {
91            fn deserialize<D>(deserializer: D) -> core::result::Result<$name, D::Error>
92            where
93                D: $crate::serde::de::Deserializer<'de>,
94            {
95                use core::fmt::Formatter;
96
97                struct Visitor;
98                impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
99                    type Value = $name;
100
101                    fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
102                        f.write_str($expecting)
103                    }
104
105                    fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
106                    where
107                        E: $crate::serde::de::Error,
108                    {
109                        v.parse::<$name>().map_err(E::custom)
110                    }
111                }
112
113                deserializer.deserialize_str(Visitor)
114            }
115        }
116    };
117}
118
119/// Implements `serde::Serialize` and `Deserialize` by way of `Display` and `FromStr` respectively.
120///
121/// `$name` is required to implement `core::fmt::Display` and `core::str::FromStr`.
122#[macro_export]
123macro_rules! serde_string_impl {
124    ($name:ty, $expecting:literal) => {
125        $crate::serde_string_deserialize_impl!($name, $expecting);
126        $crate::serde_string_serialize_impl!($name, $expecting);
127    };
128}
129
130/// A combination macro where the human-readable serialization is done like
131/// `serde_string_impl` and the non-human-readable impl is done as a struct.
132#[macro_export]
133macro_rules! serde_struct_human_string_impl {
134    ($name:ident, $expecting:literal, $($fe:ident),*) => (
135        impl<'de> $crate::serde::Deserialize<'de> for $name {
136            fn deserialize<D>(deserializer: D) -> core::result::Result<$name, D::Error>
137            where
138                D: $crate::serde::de::Deserializer<'de>,
139            {
140                if deserializer.is_human_readable() {
141                    use core::fmt::Formatter;
142
143                    struct Visitor;
144                    impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
145                        type Value = $name;
146
147                        fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
148                            f.write_str($expecting)
149                        }
150
151                        fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
152                        where
153                            E: $crate::serde::de::Error,
154                        {
155                            v.parse::<$name>().map_err(E::custom)
156                        }
157
158                    }
159
160                    deserializer.deserialize_str(Visitor)
161                } else {
162                    use core::fmt::Formatter;
163                    use $crate::serde::de::IgnoredAny;
164
165                    #[allow(non_camel_case_types)]
166                    enum Enum { Unknown__Field, $($fe),* }
167
168                    struct EnumVisitor;
169                    impl<'de> $crate::serde::de::Visitor<'de> for EnumVisitor {
170                        type Value = Enum;
171
172                        fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
173                            f.write_str("a field name")
174                        }
175
176                        fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
177                        where
178                            E: $crate::serde::de::Error,
179                        {
180                            match v {
181                                $(
182                                stringify!($fe) => Ok(Enum::$fe)
183                                ),*,
184                                _ => Ok(Enum::Unknown__Field)
185                            }
186                        }
187                    }
188
189                    impl<'de> $crate::serde::Deserialize<'de> for Enum {
190                        fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
191                        where
192                            D: $crate::serde::de::Deserializer<'de>,
193                        {
194                            deserializer.deserialize_str(EnumVisitor)
195                        }
196                    }
197
198                    struct Visitor;
199
200                    impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
201                        type Value = $name;
202
203                        fn expecting(&self, f: &mut Formatter) -> core::fmt::Result {
204                            f.write_str("a struct")
205                        }
206
207                        fn visit_seq<V>(self, mut seq: V) -> core::result::Result<Self::Value, V::Error>
208                        where
209                            V: $crate::serde::de::SeqAccess<'de>,
210                        {
211                            use $crate::serde::de::Error;
212
213                            let length = 0;
214                            $(
215                                let $fe = seq.next_element()?.ok_or_else(|| {
216                                    Error::invalid_length(length, &self)
217                                })?;
218                                #[allow(unused_variables)]
219                                let length = length + 1;
220                            )*
221
222                            let ret = $name {
223                                $($fe),*
224                            };
225
226                            Ok(ret)
227                        }
228
229                        fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
230                        where
231                            A: $crate::serde::de::MapAccess<'de>,
232                        {
233                            use $crate::serde::de::Error;
234
235                            $(let mut $fe = None;)*
236
237                            loop {
238                                match map.next_key::<Enum>()? {
239                                    Some(Enum::Unknown__Field) => {
240                                        map.next_value::<IgnoredAny>()?;
241                                    }
242                                    $(
243                                        Some(Enum::$fe) => {
244                                            $fe = Some(map.next_value()?);
245                                        }
246                                    )*
247                                    None => { break; }
248                                }
249                            }
250
251                            $(
252                                let $fe = match $fe {
253                                    Some(x) => x,
254                                    None => return Err(A::Error::missing_field(stringify!($fe))),
255                                };
256                            )*
257
258                            let ret = $name {
259                                $($fe),*
260                            };
261
262                            Ok(ret)
263                        }
264                    }
265                    // end type defs
266
267                    static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*];
268
269                    deserializer.deserialize_struct(stringify!($name), FIELDS, Visitor)
270                }
271            }
272        }
273
274        impl $crate::serde::Serialize for $name {
275            fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
276            where
277                S: $crate::serde::Serializer,
278            {
279                if serializer.is_human_readable() {
280                    serializer.collect_str(&self)
281                } else {
282                    use $crate::serde::ser::SerializeStruct;
283
284                    // Only used to get the struct length.
285                    static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*];
286
287                    let mut st = serializer.serialize_struct(stringify!($name), FIELDS.len())?;
288
289                    $(
290                        st.serialize_field(stringify!($fe), &self.$fe)?;
291                    )*
292
293                    st.end()
294                }
295            }
296        }
297    )
298}
299
300/// Does round trip test to/from serde value.
301#[cfg(feature = "test-serde")]
302#[macro_export]
303macro_rules! serde_round_trip (
304    ($var:expr) => ({
305        use serde_json;
306
307        let encoded = $crate::serde_json::to_value(&$var).expect("serde_json failed to encode");
308        let decoded = $crate::serde_json::from_value(encoded).expect("serde_json failed to decode");
309        assert_eq!($var, decoded);
310
311        let encoded = $crate::bincode::serialize(&$var).expect("bincode failed to encode");
312        let decoded = $crate::bincode::deserialize(&encoded).expect("bincode failed to decode");
313        assert_eq!($var, decoded);
314    })
315);
316
317#[cfg(feature = "hex")]
318/// Serializes a byte slice using the `hex` crate.
319pub struct SerializeBytesAsHex<'a>(pub &'a [u8]);
320
321#[cfg(feature = "hex")]
322impl serde::Serialize for SerializeBytesAsHex<'_> {
323    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
324    where
325        S: serde::Serializer,
326    {
327        use hex::DisplayHex;
328
329        serializer.collect_str(&format_args!("{:x}", self.0.as_hex()))
330    }
331}