Add SSZ encode/decode for bool
This commit is contained in:
parent
fdfaf18dbd
commit
345c527d33
@ -39,6 +39,21 @@ impl Decodable for u8 {
|
||||
}
|
||||
}
|
||||
|
||||
impl Decodable for bool {
|
||||
fn ssz_decode(bytes: &[u8], index: usize) -> Result<(Self, usize), DecodeError> {
|
||||
if index >= bytes.len() {
|
||||
Err(DecodeError::TooShort)
|
||||
} else {
|
||||
let result = match bytes[index] {
|
||||
0b0000_0000 => false,
|
||||
0b1000_0000 => true,
|
||||
_ => return Err(DecodeError::Invalid),
|
||||
};
|
||||
Ok((result, index + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Decodable for H256 {
|
||||
fn ssz_decode(bytes: &[u8], index: usize) -> Result<(Self, usize), DecodeError> {
|
||||
if bytes.len() < 32 || bytes.len() - 32 < index {
|
||||
@ -215,4 +230,20 @@ mod tests {
|
||||
let result: u16 = decode_ssz(&vec![0, 0, 0, 0, 1], 3).unwrap().0;
|
||||
assert_eq!(result, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_ssz_bool() {
|
||||
let ssz = vec![0b0000_0000, 0b1000_0000];
|
||||
let (result, index): (bool, usize) = decode_ssz(&ssz, 0).unwrap();
|
||||
assert_eq!(index, 1);
|
||||
assert_eq!(result, false);
|
||||
|
||||
let (result, index): (bool, usize) = decode_ssz(&ssz, 1).unwrap();
|
||||
assert_eq!(index, 2);
|
||||
assert_eq!(result, true);
|
||||
|
||||
let ssz = vec![0b0100_0000];
|
||||
let result: Result<(bool, usize), DecodeError> = decode_ssz(&ssz, 0);
|
||||
assert_eq!(result, Err(DecodeError::Invalid));
|
||||
}
|
||||
}
|
||||
|
@ -46,6 +46,13 @@ impl_encodable_for_uint!(u32, 32);
|
||||
impl_encodable_for_uint!(u64, 64);
|
||||
impl_encodable_for_uint!(usize, 64);
|
||||
|
||||
impl Encodable for bool {
|
||||
fn ssz_append(&self, s: &mut SszStream) {
|
||||
let byte = if *self { 0b1000_0000 } else { 0b0000_0000 };
|
||||
s.append_encoded_raw(&[byte]);
|
||||
}
|
||||
}
|
||||
|
||||
impl Encodable for H256 {
|
||||
fn ssz_append(&self, s: &mut SszStream) {
|
||||
s.append_encoded_raw(&self.to_vec());
|
||||
@ -206,4 +213,17 @@ mod tests {
|
||||
ssz.append(&x);
|
||||
assert_eq!(ssz.drain(), vec![255, 255, 255, 255, 255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ssz_encode_bool() {
|
||||
let x: bool = false;
|
||||
let mut ssz = SszStream::new();
|
||||
ssz.append(&x);
|
||||
assert_eq!(ssz.drain(), vec![0b0000_0000]);
|
||||
|
||||
let x: bool = true;
|
||||
let mut ssz = SszStream::new();
|
||||
ssz.append(&x);
|
||||
assert_eq!(ssz.drain(), vec![0b1000_0000]);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user