tendermint/serializers/
option_hash.rs

1//! `Option<Hash>` serialization with validation
2
3use alloc::borrow::Cow;
4
5use serde::{de, Deserialize, Deserializer, Serializer};
6
7use super::hash;
8use crate::{hash::Algorithm, Hash};
9
10/// Deserialize a nullable hexstring into `Option<Hash>`.
11/// A null value is deserialized as `None`.
12pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Hash>, D::Error>
13where
14    D: Deserializer<'de>,
15{
16    match Option::<Cow<'_, str>>::deserialize(deserializer)? {
17        Some(s) => Hash::from_hex_upper(Algorithm::Sha256, &s)
18            .map(Some)
19            .map_err(de::Error::custom),
20        None => Ok(None),
21    }
22}
23
24/// Serialize from `Option<Hash>` into a nullable hexstring. None is serialized as null.
25pub fn serialize<S>(value: &Option<Hash>, serializer: S) -> Result<S::Ok, S::Error>
26where
27    S: Serializer,
28{
29    if value.is_none() {
30        serializer.serialize_none()
31    } else {
32        // hash::serialize serializes as Option<String>, so this is consistent
33        // with the other branch.
34        hash::serialize(value.as_ref().unwrap(), serializer)
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn none_round_trip() {
44        let v: Option<Hash> = None;
45        let json = serde_json::to_string(&v).unwrap();
46        let parsed: Option<Hash> = serde_json::from_str(&json).unwrap();
47        assert!(parsed.is_none());
48    }
49}