From: Matt Corallo Date: Tue, 22 Nov 2022 21:55:39 +0000 (+0000) Subject: Implement (de)serialization for BTreeMap same as HashMap X-Git-Tag: v0.0.114-beta~53^2~3 X-Git-Url: http://git.bitcoin.ninja/?a=commitdiff_plain;h=7fd9b33c09d09f83c1712b1d8348cc0c67eee746;p=rust-lightning Implement (de)serialization for BTreeMap same as HashMap --- diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index a656604d4..454c4990e 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -22,6 +22,8 @@ use core::cmp; use core::convert::TryFrom; use core::ops::Deref; +use alloc::collections::BTreeMap; + use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE}; use bitcoin::secp256k1::ecdsa; @@ -588,43 +590,47 @@ impl<'a, T> From<&'a Vec> for WithoutLength<&'a Vec> { fn from(v: &'a Vec) -> Self { Self(v) } } -// HashMap -impl Writeable for HashMap - where K: Writeable + Eq + Hash, - V: Writeable -{ - #[inline] - fn write(&self, w: &mut W) -> Result<(), io::Error> { - (self.len() as u16).write(w)?; - for (key, value) in self.iter() { - key.write(w)?; - value.write(w)?; +macro_rules! impl_for_map { + ($ty: ident, $keybound: ident, $constr: expr) => { + impl Writeable for $ty + where K: Writeable + Eq + $keybound, V: Writeable + { + #[inline] + fn write(&self, w: &mut W) -> Result<(), io::Error> { + (self.len() as u16).write(w)?; + for (key, value) in self.iter() { + key.write(w)?; + value.write(w)?; + } + Ok(()) + } } - Ok(()) - } -} -impl Readable for HashMap - where K: Readable + Eq + Hash, - V: MaybeReadable -{ - #[inline] - fn read(r: &mut R) -> Result { - let len: u16 = Readable::read(r)?; - let mut ret = HashMap::with_capacity(len as usize); - for _ in 0..len { - let k = K::read(r)?; - let v_opt = V::read(r)?; - if let Some(v) = v_opt { - if ret.insert(k, v).is_some() { - return Err(DecodeError::InvalidValue); + impl Readable for $ty + where K: Readable + Eq + $keybound, V: MaybeReadable + { + #[inline] + fn read(r: &mut R) -> Result { + let len: u16 = Readable::read(r)?; + let mut ret = $constr(len as usize); + for _ in 0..len { + let k = K::read(r)?; + let v_opt = V::read(r)?; + if let Some(v) = v_opt { + if ret.insert(k, v).is_some() { + return Err(DecodeError::InvalidValue); + } + } } + Ok(ret) } } - Ok(ret) } } +impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new()); +impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len)); + // HashSet impl Writeable for HashSet where T: Writeable + Eq + Hash