Add support for SSZ union type via Option

This commit is contained in:
Paul Hauner
2019-06-04 12:03:54 +10:00
parent 7005234fd1
commit 7a2ab2e9aa
5 changed files with 141 additions and 1 deletions

View File

@@ -25,6 +25,23 @@ impl_encodable_for_uint!(u32, 32);
impl_encodable_for_uint!(u64, 64);
impl_encodable_for_uint!(usize, 64);
/// The SSZ "union" type.
impl<T: Encode> Encode for Option<T> {
fn is_ssz_fixed_len() -> bool {
false
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
match self {
None => buf.append(&mut encode_union_index(0)),
Some(t) => {
buf.append(&mut encode_union_index(1));
t.ssz_append(buf);
}
}
}
}
impl<T: Encode> Encode for Vec<T> {
fn is_ssz_fixed_len() -> bool {
false
@@ -168,6 +185,25 @@ mod tests {
);
}
#[test]
fn ssz_encode_option_u16() {
assert_eq!(Some(65535_u16).as_ssz_bytes(), vec![1, 0, 0, 0, 255, 255]);
let none: Option<u16> = None;
assert_eq!(none.as_ssz_bytes(), vec![0, 0, 0, 0]);
}
#[test]
fn ssz_encode_option_vec_u16() {
assert_eq!(
Some(vec![0_u16, 1]).as_ssz_bytes(),
vec![1, 0, 0, 0, 0, 0, 1, 0]
);
let none: Option<Vec<u16>> = None;
assert_eq!(none.as_ssz_bytes(), vec![0, 0, 0, 0]);
}
#[test]
fn ssz_encode_u8() {
assert_eq!(0_u8.as_ssz_bytes(), vec![0]);