Browse Source

Added more tests to the serializer.

Matthew Carr 3 years ago
parent
commit
1addd3e2ff
2 changed files with 85 additions and 16 deletions
  1. 6 1
      crates/node/src/serde_blocktree/error.rs
  2. 79 15
      crates/node/src/serde_blocktree/ser.rs

+ 6 - 1
crates/node/src/serde_blocktree/error.rs

@@ -10,6 +10,7 @@ pub enum Error {
     Eof,
     UnknownLength,
     SequenceTooLong(usize),
+    TooManyVariants(u32),
 }
 
 impl std::error::Error for Error {}
@@ -22,7 +23,11 @@ impl Display for Error {
             Error::Eof => formatter.write_str("unexpected end of input"),
             Error::UnknownLength => formatter.write_str("sequence had an unknown length"),
             Error::SequenceTooLong(length) => formatter.write_fmt(
-                format_args!("sequence was longer than 2**32 - 1: {}", length)),
+                format_args!("sequence was longer than 2**32 - 1: {}", length)
+            ),
+            Error::TooManyVariants(length) => formatter.write_fmt(
+                format_args!("too many variants to be serialized, the limit is 2**16: {}", length)
+            ),
         }
     }
 }

+ 79 - 15
crates/node/src/serde_blocktree/ser.rs

@@ -38,6 +38,10 @@ fn try_convert(len: Option<usize>) -> Result<u32> {
     }
 }
 
+fn convert_variant_index(index: u32) -> Result<u16> {
+    u16::try_from(index).or_else(|_| Err(Error::TooManyVariants(index)))
+}
+
 impl<'a, T: Write> ser::Serializer for &'a mut Serializer<T> {
     type Ok = Ok;
     type Error = Error;
@@ -184,7 +188,8 @@ impl<'a, T: Write> ser::Serializer for &'a mut Serializer<T> {
     fn serialize_unit_variant(
         self, _name: &'static str, variant_index: u32, _variant: &'static str
     ) -> Result<Self::Ok> {
-        self.serialize_u32(variant_index)?;
+        let index = convert_variant_index(variant_index)?;
+        self.serialize_u16(index)?;
         Ok(())
     }
 
@@ -201,7 +206,8 @@ impl<'a, T: Write> ser::Serializer for &'a mut Serializer<T> {
     fn serialize_newtype_variant<U: ?Sized + Serialize>(
         self, _name: &'static str, variant_index: u32, _variant: &'static str, value: &U
     ) -> Result<Self::Ok> {
-        self.serialize_u32(variant_index)?;
+        let index = convert_variant_index(variant_index)?;
+        self.serialize_u16(index)?;
         value.serialize(self)?;
         Ok(())
     }
@@ -228,7 +234,8 @@ impl<'a, T: Write> ser::Serializer for &'a mut Serializer<T> {
     fn serialize_tuple_variant(
         self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize
     ) -> Result<Self::SerializeTupleStruct> {
-        self.serialize_u32(variant_index)?;
+        let index = convert_variant_index(variant_index)?;
+        self.serialize_u16(index)?;
         Ok(self)
     }
 
@@ -250,7 +257,8 @@ impl<'a, T: Write> ser::Serializer for &'a mut Serializer<T> {
     fn serialize_struct_variant(
         self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize
     ) -> Result<Self::SerializeStructVariant> {
-        self.serialize_u32(variant_index)?;
+        let index = convert_variant_index(variant_index)?;
+        self.serialize_u16(index)?;
         Ok(self)
     }
 }
@@ -374,6 +382,7 @@ mod test {
         EnvelopedKey
     };
     use serde::Serialize;
+    use std::collections::HashMap;
 
     #[test]
     fn serialize_bool() -> Result<()> {
@@ -545,7 +554,7 @@ mod test {
 
     #[test]
     fn serialize_some() -> Result<()> {
-        // Sometimes I use decimal sometimes I use hex. So what, what to fight about it?
+        // Sometimes I use decimal, sometimes I use hex. So what, want to fight about it?
         let some: Option<i32> = Option::Some(0x02D8);
         let buffer = super::to_vec(&some)?;
         assert_eq!(vec![0xD8, 0x02, 0x00, 0x00], buffer);
@@ -573,17 +582,19 @@ mod test {
     }
 
     #[test]
-    fn serialize_unit_struct_variant() -> Result<()> {
+    fn serialize_unit_variant() -> Result<()> {
         #[derive(Serialize)]
-        enum UnitStructVariant {
-            Zeroth {},
-            First {},
-            Second {},
-            Third {}
+        enum Matter {
+            Condensate,
+            Solid,
+            Liquid,
+            Gas,
+            Plasma,
+            Cat,
         }
-        let test = UnitStructVariant::Second {};
+        let test = Matter::Liquid;
         let buffer = super::to_vec(&test)?;
-        assert_eq!(vec![2, 0, 0, 0], buffer);
+        assert_eq!(vec![0x02, 0x00], buffer);
         Ok(())
     }
 
@@ -609,18 +620,33 @@ mod test {
         let value = Currency::Fil(1024);
         let buffer = super::to_vec(&value)?;
         let expected = vec![
-            0x02, 0x00, 0x00, 0x00, // The variant index.
+            0x02, 0x00, // The variant index.
             0x00, 0x04, 0x00, 0x00  // The value contained within.
         ];
         assert_eq!(expected, buffer);
         Ok(())
     }
 
+    #[test]
+    fn serialize_unit_struct_variant() -> Result<()> {
+        #[derive(Serialize)]
+        enum UnitStructVariant {
+            Zeroth {},
+            First {},
+            Second {},
+            Third {}
+        }
+        let test = UnitStructVariant::Second {};
+        let buffer = super::to_vec(&test)?;
+        assert_eq!(vec![2, 0], buffer);
+        Ok(())
+    }
+
     #[test]
     fn serialize_tuple() -> Result<()> {
         let value = (5u16, -1i8);
         let buffer = super::to_vec(&value)?;
-        assert_eq!(vec![0x05, 0x00, 0xFF], buffer);
+        assert_eq!(vec![0x05, 0x00 /* == 5u16 */, 0xFF /* == -1i8 */], buffer);
         Ok(())
     }
 
@@ -638,4 +664,42 @@ mod test {
         assert_eq!(expected, buffer);
         Ok(())
     }
+
+    #[test]
+    fn serialize_tuple_variant() -> Result<()> {
+        #[derive(Serialize)]
+        enum ByteVector {
+            Dim2(u8, u8),
+            Dim3(u8, u8, u8),
+        }
+        let value = ByteVector::Dim3(5, 9, 42);
+        let buffer = super::to_vec(&value)?;
+        let expected = vec![
+            0x01, 0x00, // The variant index.
+            0x05, // The first entry.
+            0x09, // The second entry.
+            0x2A, // The last entry.
+        ];
+        assert_eq!(expected, buffer);
+        Ok(())
+    }
+
+    #[test]
+    fn serialize_map() -> Result<()> {
+        #[derive(PartialEq, Eq, Hash, Serialize)]
+        enum Color { Red, Blue }
+        let mut map: HashMap<Color, u16> = HashMap::new();
+        map.insert(Color::Red, 5);
+        map.insert(Color::Blue, 7);
+        let buffer = super::to_vec(&map)?;
+        let expected = vec![
+            0x02, 0x00, 0x00, 0x00, // Number of entries.
+            0x00, 0x00, // First key.
+            0x05, 0x00, // First value.
+            0x01, 0x00, // Second key.
+            0x07, 0x00, // Second value.
+        ];
+        assert_eq!(expected, buffer);
+        Ok(())
+    }
 }