Implement `HashMap` read for `MaybeReadable` values
authorMatt Corallo <git@bluematt.me>
Sun, 3 Oct 2021 00:46:10 +0000 (00:46 +0000)
committerMatt Corallo <git@bluematt.me>
Fri, 22 Oct 2021 18:41:42 +0000 (18:41 +0000)
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.

lightning/src/util/ser.rs

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