serde_utils/
hex_vec.rs

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