summaryrefslogtreecommitdiff
path: root/src/serde.rs
blob: 76676d78ec76ca4bed90f7c4bce54f0385d4dbdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
pub mod as_hex {
    use serde::{de, Deserialize, Deserializer, Serializer};

    pub fn serialize<const N: usize, S: Serializer>(
        b: &[u8; N],
        ser: S,
    ) -> Result<S::Ok, S::Error> {
        ser.serialize_str(&hex::encode(b))
    }

    pub fn deserialize<'de, const N: usize, D: Deserializer<'de>>(
        des: D,
    ) -> Result<[u8; N], D::Error> {
        let raw = <String as Deserialize>::deserialize(des)?;
        let mut result = [0; N];
        hex::decode_to_slice(&raw, &mut result).map_err(|_| {
            de::Error::invalid_value(de::Unexpected::Other("non-hex string"), &"a hex string")
        })?;
        Ok(result)
    }
}