serde_utils/
u32_hex.rs

1//! Formats `u32` as a 0x-prefixed, little-endian hex string.
2//!
3//! E.g., `0` serializes as `"0x00000000"`.
4
5use crate::bytes_4_hex;
6use serde::{Deserializer, Serializer};
7
8pub fn serialize<S>(num: &u32, serializer: S) -> Result<S::Ok, S::Error>
9where
10    S: Serializer,
11{
12    let hex = format!("0x{}", hex::encode(num.to_le_bytes()));
13    serializer.serialize_str(&hex)
14}
15
16pub fn deserialize<'de, D>(deserializer: D) -> Result<u32, D::Error>
17where
18    D: Deserializer<'de>,
19{
20    bytes_4_hex::deserialize(deserializer).map(u32::from_le_bytes)
21}
22
23#[cfg(test)]
24pub mod test {
25    use serde::{Deserialize, Serialize};
26
27    #[derive(Debug, PartialEq, Serialize, Deserialize)]
28    #[serde(transparent)]
29    struct Wrapper {
30        #[serde(with = "super")]
31        val: u32,
32    }
33
34    #[test]
35    fn encoding() {
36        assert_eq!(
37            &serde_json::to_string(&Wrapper { val: 0 }).unwrap(),
38            "\"0x00000000\""
39        );
40        assert_eq!(
41            &serde_json::to_string(&Wrapper { val: 5 }).unwrap(),
42            "\"0x05000000\""
43        );
44
45        assert_eq!(
46            &serde_json::to_string(&Wrapper { val: u32::MAX }).unwrap(),
47            "\"0xffffffff\""
48        );
49    }
50
51    #[test]
52    fn decoding() {
53        assert_eq!(
54            serde_json::from_str::<Wrapper>("\"0x00000000\"").unwrap(),
55            Wrapper { val: 0 },
56        );
57        assert_eq!(
58            serde_json::from_str::<Wrapper>("\"0x05000000\"").unwrap(),
59            Wrapper { val: 5 },
60        );
61        assert_eq!(
62            serde_json::from_str::<Wrapper>("\"0xffffffff\"").unwrap(),
63            Wrapper { val: u32::MAX },
64        );
65
66        // Wrong length.
67        serde_json::from_str::<Wrapper>("\"0xfffffffff\"").unwrap_err();
68        // Requires 0x.
69        serde_json::from_str::<Wrapper>("\"00000000\"").unwrap_err();
70    }
71}