From 047c0a1f916b69e767ddfb8d055e454bc457844e Mon Sep 17 00:00:00 2001 From: Remco Bloemen Date: Thu, 17 Mar 2022 16:06:47 -0700 Subject: [PATCH] Test serializer --- Cargo.toml | 5 ++--- src/util.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ecc14db..0ada42f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,9 +54,8 @@ zkp-u256 = { version = "0.2", optional = true } # TODO: Remove ethers-core = { git = "https://github.com/gakonst/ethers-rs", default-features = false } [dev-dependencies] -pretty_assertions = "1.0" -rand_chacha = "0.3.1" -rand_core = "0.6.3" +bincode = "1.3.3" +proptest = "1.0" serde_json = "1.0.79" tempfile = "3.0" tiny-keccak = "2.0.2" diff --git a/src/util.rs b/src/util.rs index 698f638..e78dd81 100644 --- a/src/util.rs +++ b/src/util.rs @@ -56,6 +56,7 @@ fn trim_hex_prefix(str: &str) -> &str { } } +/// Helper to deserialize byte arrays. pub(crate) fn deserialize_bytes<'de, const N: usize, D: Deserializer<'de>>( deserializer: D, ) -> Result<[u8; N], D::Error> { @@ -100,3 +101,31 @@ pub(crate) fn deserialize_bytes<'de, const N: usize, D: Deserializer<'de>>( deserializer.deserialize_bytes(ByteVisitor) } } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_serialize_bytes_hex() { + let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + let mut ser = serde_json::Serializer::new(Vec::new()); + serialize_bytes::<16, 34, _>(&mut ser, &bytes).unwrap(); + let json = ser.into_inner(); + assert_eq!(json, b"\"0x0102030405060708090a0b0c0d0e0f10\""); + } + + #[test] + fn test_serialize_bytes_bin() { + let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + let mut bin: Vec = Vec::new(); + { + let mut ser = bincode::Serializer::new(&mut bin, bincode::options()); + serialize_bytes::<16, 34, _>(&mut ser, &bytes).unwrap(); + } + // Bincode appears to prefix with a length. + assert_eq!(bin, [ + 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]); + } +}