types: use untagged serialization for Parents

Summary:
Tell serde to use an [untagged representation](https://serde.rs/enum-representations.html#untagged) of this enum. This means that `Parents::None` will map to a null value, `Parents::One` will map to an array representing a `Node`, and a `Parents::Two` will map to an array of 2 arrays representing `Node`.

Using CBOR serialization, this means that these variants are 1 byte, 21 bytes, and 43 bytes respectively.

Differential Revision: D14174309

fbshipit-source-id: 0217a23c4ee5409ab293525d7b6e5ae969b5504d
This commit is contained in:
Arun Kulshreshtha 2019-02-21 16:27:37 -08:00 committed by Facebook Github Bot
parent eb3b97d91a
commit 09d3ade23a
2 changed files with 45 additions and 2 deletions

View File

@ -10,11 +10,13 @@ for-tests = ["rand", "quickcheck"]
[dependencies]
failure = "0.1.3"
failure_derive = "0.1.3"
quickcheck = { version = "0.6.2", optional = true }
rand = { version = "0.5.5", optional = true }
serde = "1.0.84"
serde_derive = "1.0.84"
quickcheck = { version = "0.6.2", optional = true }
[dev-dependencies]
rand = "0.5.5"
quickcheck = "0.6.2"
rand = "0.5.5"
serde_cbor = "0.9.0"
serde_json = "1.0.38"

View File

@ -25,6 +25,7 @@ use crate::node::{Node, NULL_ID};
Serialize,
Deserialize
)]
#[serde(untagged)]
pub enum Parents {
None,
One(Node),
@ -143,6 +144,9 @@ impl Arbitrary for Parents {
mod tests {
use super::*;
use serde_cbor;
use serde_json::{self, json};
#[test]
fn from_iter() {
let none = Parents::from_iter(vec![NULL_ID, NULL_ID]);
@ -180,4 +184,41 @@ mod tests {
let two = parents.into_iter().collect::<Vec<_>>();
assert_eq!(two, vec![p1, p2]);
}
#[test]
fn untagged_serializtaion() {
let parents = Parents::None;
let none = serde_json::to_value(&parents).unwrap();
assert_eq!(none, json!(null));
let p1 = Node::from_byte_array([0x1; 20]);
let parents = Parents::One(p1);
let one = serde_json::to_value(&parents).unwrap();
let expected = json!([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
assert_eq!(one, expected);
let p2 = Node::from_byte_array([0x2; 20]);
let parents = Parents::Two(p1, p2);
let two = serde_json::to_value(&parents).unwrap();
let p1_json = json!([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
let p2_json = json!([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]);
assert_eq!(two, json!([p1_json, p2_json]));
}
#[test]
fn serialized_size_cbor() {
let parents = Parents::None;
let none = serde_cbor::to_vec(&parents).unwrap();
assert_eq!(none.len(), 1);
let p1 = Node::from_byte_array([0x1; 20]);
let parents = Parents::One(p1);
let one = serde_cbor::to_vec(&parents).unwrap();
assert_eq!(one.len(), 21);
let p2 = Node::from_byte_array([0x2; 20]);
let parents = Parents::Two(p1, p2);
let two = serde_cbor::to_vec(&parents).unwrap();
assert_eq!(two.len(), 43);
}
}