diff --git a/src/serialization.rs b/src/serialization.rs index 375b6db..d744edc 100644 --- a/src/serialization.rs +++ b/src/serialization.rs @@ -109,3 +109,48 @@ pub mod outpoint_map { } } +// Custom module for converting a BTreeMap using hex conversion. +pub mod hex_array_btree { + use super::*; + + // Serializes a BTreeMap as a BTreeMap + // where the value is a hex-encoded string. + pub fn serialize( + map: &BTreeMap, + serializer: S, + ) -> Result + where + S: Serializer, + { + // Convert each [u8; 32] to a hex string. + let hex_map: BTreeMap = map + .iter() + .map(|(k, v)| (k.clone(), v.to_lower_hex_string())) + .collect(); + hex_map.serialize(serializer) + } + + // Deserializes a BTreeMap from a BTreeMap + // where the value is expected to be a hex-encoded string. + pub fn deserialize<'de, D>( + deserializer: D, + ) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // Deserialize into a temporary map with hex string values. + let hex_map: BTreeMap = BTreeMap::deserialize(deserializer)?; + let mut map = BTreeMap::new(); + // Convert each hex string back into a [u8; 32]. + for (key, hex_str) in hex_map { + let bytes = Vec::from_hex(&hex_str).map_err(D::Error::custom)?; + if bytes.len() != 32 { + return Err(D::Error::custom("Invalid length for [u8;32]")); + } + let mut array = [0u8; 32]; + array.copy_from_slice(&bytes); + map.insert(key, array); + } + Ok(map) + } +}