bitcoin_internals/
serde.rs

1//! Contains extensions of `serde` and internal reexports.
2
3#[cfg(feature = "serde")]
4#[doc(hidden)]
5pub use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};
6
7/// Converts given error type to a type implementing [`de::Error`].
8///
9/// This is used in [`Deserialize`] implementations to convert specialized errors into serde
10/// errors.
11#[cfg(feature = "serde")]
12pub trait IntoDeError: Sized {
13    /// Converts to deserializer error possibly outputting vague message.
14    ///
15    /// This method is allowed to return a vague error message if the error type doesn't contain
16    /// enough information to explain the error precisely.
17    fn into_de_error<E: de::Error>(self, expected: Option<&dyn de::Expected>) -> E;
18
19    /// Converts to deserializer error without outputting vague message.
20    ///
21    /// If the error type doesn't contain enough information to explain the error precisely this
22    /// should return `Err(self)` allowing the caller to use its information instead.
23    fn try_into_de_error<E>(self, expected: Option<&dyn de::Expected>) -> Result<E, Self>
24    where
25        E: de::Error,
26    {
27        Ok(self.into_de_error(expected))
28    }
29}
30
31#[cfg(feature = "serde")]
32mod impls {
33    use super::*;
34
35    impl IntoDeError for core::convert::Infallible {
36        fn into_de_error<E: de::Error>(self, _expected: Option<&dyn de::Expected>) -> E {
37            match self {}
38        }
39    }
40
41    impl IntoDeError for core::num::ParseIntError {
42        fn into_de_error<E: de::Error>(self, expected: Option<&dyn de::Expected>) -> E {
43            self.try_into_de_error(expected).unwrap_or_else(|_| {
44                let expected = expected.unwrap_or(&"an integer");
45
46                E::custom(format_args!("invalid string, expected {}", expected))
47            })
48        }
49
50        fn try_into_de_error<E>(self, expected: Option<&dyn de::Expected>) -> Result<E, Self>
51        where
52            E: de::Error,
53        {
54            use core::num::IntErrorKind::Empty;
55
56            let expected = expected.unwrap_or(&"an integer");
57
58            match self.kind() {
59                Empty => Ok(E::invalid_value(de::Unexpected::Str(""), expected)),
60                _ => Err(self),
61            }
62        }
63    }
64}