Browse Source

scr/util/serial: added BTreeMap Generic encoding

aggstam 4 years ago
parent
commit
0e2929a5c8
2 changed files with 27 additions and 25 deletions
  1. 1 24
      src/consensus/participant.rs
  2. 26 1
      src/util/serial.rs

+ 1 - 24
src/consensus/participant.rs

@@ -1,4 +1,4 @@
-use std::{collections::BTreeMap, io};
+use std::io;
 
 use crate::{
     crypto::{address::Address, keypair::PublicKey},
@@ -35,27 +35,4 @@ impl net::Message for Participant {
     }
 }
 
-impl Encodable for BTreeMap<Address, Participant> {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let mut len = 0;
-        len += VarInt(self.len() as u64).encode(&mut s)?;
-        for c in self.iter() {
-            len += c.1.encode(&mut s)?;
-        }
-        Ok(len)
-    }
-}
-
-impl Decodable for BTreeMap<Address, Participant> {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        let len = VarInt::decode(&mut d)?.0;
-        let mut ret = BTreeMap::new();
-        for _ in 0..len {
-            let participant: Participant = Decodable::decode(&mut d)?;
-            ret.insert(participant.address, participant);
-        }
-        Ok(ret)
-    }
-}
-
 impl_vec!(Participant);

+ 26 - 1
src/util/serial.rs

@@ -1,7 +1,7 @@
 use fxhash::FxHashMap;
 use std::{
     borrow::Cow,
-    collections::HashSet,
+    collections::{BTreeMap, HashSet},
     io,
     io::{Cursor, Read, Write},
     mem,
@@ -695,6 +695,31 @@ impl<T: Decodable + std::cmp::Eq + std::hash::Hash, U: Decodable> Decodable for
     }
 }
 
+impl<T: Encodable, U: Encodable> Encodable for BTreeMap<T, U> {
+    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
+        let mut len = 0;
+        len += VarInt(self.len() as u64).encode(&mut s)?;
+        for c in self.iter() {
+            len += c.0.encode(&mut s)?;
+            len += c.1.encode(&mut s)?;
+        }
+        Ok(len)
+    }
+}
+
+impl<T: Decodable + std::cmp::Ord, U: Decodable> Decodable for BTreeMap<T, U> {
+    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
+        let len = VarInt::decode(&mut d)?.0;
+        let mut ret = BTreeMap::new();
+        for _ in 0..len {
+            let key: T = Decodable::decode(&mut d)?;
+            let entry: U = Decodable::decode(&mut d)?;
+            ret.insert(key, entry);
+        }
+        Ok(ret)
+    }
+}
+
 // Tuples
 macro_rules! tuple_encode {
     ($($x:ident),*) => (