value: Add serialize_list_or_set function
Add a function that can be used to serialize both a list and a set.
It takes only an iterator, which allows it with many different types.
Thanks to this we can avoid code duplication when implementing
Value for HashSet in the following commit.
@@ -447,20 +447,17 @@ fn serialize_map<K: Value, V: Value>(
Ok(())
}
-impl<K: Value, V: Value> Value for HashMap<K, V> {
- fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
- serialize_map(self.iter(), self.len(), buf)
- }
-}
-
-impl<T: Value> Value for Vec<T> {
- fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
+fn serialize_list_or_set<'a, V: 'a + Value>(
+ elements_iter: impl Iterator<Item = &'a V>,
+ element_count: usize,
+ buf: &mut Vec<u8>,
+) -> Result<(), ValueTooBig> {
let bytes_num_pos: usize = buf.len();
buf.put_i32(0);
- buf.put_i32(self.len().try_into().map_err(|_| ValueTooBig)?);
- for value in self {
- <T as Value>::serialize(value, buf)?;
+ buf.put_i32(element_count.try_into().map_err(|_| ValueTooBig)?);
+ for value in elements_iter {
+ <V as Value>::serialize(value, buf)?;
}
let written_bytes: usize = buf.len() - bytes_num_pos - 4;
@@ -469,6 +466,17 @@ impl<T: Value> Value for Vec<T> {
Ok(())
}
+
+impl<K: Value, V: Value> Value for HashMap<K, V> {
+ fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
+ serialize_map(self.iter(), self.len(), buf)
+ }
+}
+
+impl<T: Value> Value for Vec<T> {
+ fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
+ serialize_list_or_set(self.iter(), self.len(), buf)
+ }
}
fn serialize_tuple<V: Value>(
