Implement HashMap read for MaybeReadable values

This allows us to read a `HashMap` that has values which may be
skipped if they are some backwards-compatibility type.

We also take this opportunity to fail deserialization if keys are
duplicated.
This commit is contained in:
Matt Corallo 2021-10-03 00:46:10 +00:00
parent fcb178faeb
commit f5b6e7f58a

View file

@ -502,14 +502,20 @@ impl<K, V> Writeable for HashMap<K, V>
impl<K, V> Readable for HashMap<K, V> impl<K, V> Readable for HashMap<K, V>
where K: Readable + Eq + Hash, where K: Readable + Eq + Hash,
V: Readable V: MaybeReadable
{ {
#[inline] #[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> { fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: u16 = Readable::read(r)?; let len: u16 = Readable::read(r)?;
let mut ret = HashMap::with_capacity(len as usize); let mut ret = HashMap::with_capacity(len as usize);
for _ in 0..len { for _ in 0..len {
ret.insert(K::read(r)?, V::read(r)?); 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)
} }