lowercase_hex/
serde.rs

1//! Hex encoding with [`serde`].
2//!
3//! # Examples
4//!
5//! ```
6//! # #[cfg(feature = "alloc")] {
7//! use serde::{Serialize, Deserialize};
8//!
9//! #[derive(Serialize, Deserialize)]
10//! struct Foo {
11//!     #[serde(with = "lowercase_hex")]
12//!     bar: Vec<u8>,
13//! }
14//! # }
15//! ```
16
17use crate::FromHex;
18use core::fmt;
19use core::marker::PhantomData;
20use serde::de::{Error, Visitor};
21use serde::Deserializer;
22
23#[cfg(feature = "alloc")]
24mod serialize {
25    use serde::Serializer;
26
27    /// Serializes `data` as hex string using lowercase characters.
28    ///
29    /// Lowercase characters are used (e.g. `f9b4ca`). The resulting string's length
30    /// is always even, each byte in data is always encoded using two hex digits.
31    /// Thus, the resulting string contains exactly twice as many bytes as the input
32    /// data.
33    #[inline]
34    pub fn serialize<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error>
35    where
36        S: Serializer,
37        T: AsRef<[u8]>,
38    {
39        serializer.serialize_str(&crate::encode(data.as_ref()))
40    }
41}
42
43#[cfg(feature = "alloc")]
44pub use serialize::serialize;
45
46/// Deserializes a hex string into raw bytes.
47///
48/// Both, upper and lower case characters are valid in the input string and can
49/// even be mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings).
50#[inline]
51pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
52where
53    D: Deserializer<'de>,
54    T: FromHex,
55    <T as FromHex>::Error: fmt::Display,
56{
57    struct HexStrVisitor<T>(PhantomData<T>);
58
59    impl<T> Visitor<'_> for HexStrVisitor<T>
60    where
61        T: FromHex,
62        <T as FromHex>::Error: fmt::Display,
63    {
64        type Value = T;
65
66        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67            f.write_str("a hex encoded string")
68        }
69
70        fn visit_bytes<E: Error>(self, data: &[u8]) -> Result<Self::Value, E> {
71            FromHex::from_hex(data).map_err(Error::custom)
72        }
73
74        fn visit_str<E: Error>(self, data: &str) -> Result<Self::Value, E> {
75            FromHex::from_hex(data.as_bytes()).map_err(Error::custom)
76        }
77    }
78
79    deserializer.deserialize_str(HexStrVisitor(PhantomData))
80}