Add serialization hex_array_btree

This commit is contained in:
NicolasCantu 2025-03-12 10:20:10 +01:00 committed by Nicolas Cantu
parent 1f67eff723
commit f20a95ad56

View File

@ -109,3 +109,48 @@ pub mod outpoint_map {
}
}
// Custom module for converting a BTreeMap<String, [u8;32]> using hex conversion.
pub mod hex_array_btree {
use super::*;
// Serializes a BTreeMap<String, [u8; 32]> as a BTreeMap<String, String>
// where the value is a hex-encoded string.
pub fn serialize<S>(
map: &BTreeMap<String, [u8; 32]>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Convert each [u8; 32] to a hex string.
let hex_map: BTreeMap<String, String> = map
.iter()
.map(|(k, v)| (k.clone(), v.to_lower_hex_string()))
.collect();
hex_map.serialize(serializer)
}
// Deserializes a BTreeMap<String, [u8; 32]> from a BTreeMap<String, String>
// where the value is expected to be a hex-encoded string.
pub fn deserialize<'de, D>(
deserializer: D,
) -> Result<BTreeMap<String, [u8; 32]>, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize into a temporary map with hex string values.
let hex_map: BTreeMap<String, String> = 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)
}
}