2019-05-13 05:12:19 +00:00
|
|
|
use ssz::{Decode, DecodeError, Encode, SszDecoderBuilder, SszEncoder};
|
2019-05-03 07:39:51 +00:00
|
|
|
|
2019-05-03 07:50:29 +00:00
|
|
|
#[derive(Debug, PartialEq)]
|
2019-05-03 07:39:51 +00:00
|
|
|
pub struct Foo {
|
|
|
|
a: u16,
|
|
|
|
b: Vec<u8>,
|
|
|
|
c: u16,
|
|
|
|
}
|
|
|
|
|
2019-05-13 05:12:19 +00:00
|
|
|
impl Encode for Foo {
|
2019-05-03 07:39:51 +00:00
|
|
|
fn is_ssz_fixed_len() -> bool {
|
2019-05-13 05:12:19 +00:00
|
|
|
<u16 as Encode>::is_ssz_fixed_len() && <Vec<u16> as Encode>::is_ssz_fixed_len()
|
2019-05-03 07:39:51 +00:00
|
|
|
}
|
|
|
|
|
2019-09-08 16:23:37 +00:00
|
|
|
fn ssz_bytes_len(&self) -> usize {
|
|
|
|
<u16 as Encode>::ssz_fixed_len()
|
|
|
|
+ ssz::BYTES_PER_LENGTH_OFFSET
|
|
|
|
+ <u16 as Encode>::ssz_fixed_len()
|
|
|
|
+ self.b.ssz_bytes_len()
|
|
|
|
}
|
|
|
|
|
2019-05-05 22:47:49 +00:00
|
|
|
fn ssz_append(&self, buf: &mut Vec<u8>) {
|
2019-05-13 05:12:19 +00:00
|
|
|
let offset = <u16 as Encode>::ssz_fixed_len()
|
|
|
|
+ <Vec<u16> as Encode>::ssz_fixed_len()
|
|
|
|
+ <u16 as Encode>::ssz_fixed_len();
|
2019-05-03 07:39:51 +00:00
|
|
|
|
2019-05-05 23:58:31 +00:00
|
|
|
let mut encoder = SszEncoder::container(buf, offset);
|
2019-05-03 07:39:51 +00:00
|
|
|
|
2019-05-05 23:01:28 +00:00
|
|
|
encoder.append(&self.a);
|
|
|
|
encoder.append(&self.b);
|
|
|
|
encoder.append(&self.c);
|
2019-05-05 22:47:49 +00:00
|
|
|
|
2019-05-05 23:58:31 +00:00
|
|
|
encoder.finalize();
|
2019-05-03 07:39:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-13 05:12:19 +00:00
|
|
|
impl Decode for Foo {
|
2019-05-03 07:39:51 +00:00
|
|
|
fn is_ssz_fixed_len() -> bool {
|
2019-05-13 05:12:19 +00:00
|
|
|
<u16 as Decode>::is_ssz_fixed_len() && <Vec<u16> as Decode>::is_ssz_fixed_len()
|
2019-05-03 07:39:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
|
|
|
|
let mut builder = SszDecoderBuilder::new(bytes);
|
|
|
|
|
|
|
|
builder.register_type::<u16>()?;
|
|
|
|
builder.register_type::<Vec<u8>>()?;
|
|
|
|
builder.register_type::<u16>()?;
|
|
|
|
|
|
|
|
let mut decoder = builder.build()?;
|
|
|
|
|
|
|
|
Ok(Self {
|
|
|
|
a: decoder.decode_next()?,
|
|
|
|
b: decoder.decode_next()?,
|
|
|
|
c: decoder.decode_next()?,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2019-09-30 03:58:45 +00:00
|
|
|
let my_foo = Foo {
|
2019-05-03 07:39:51 +00:00
|
|
|
a: 42,
|
|
|
|
b: vec![0, 1, 2, 3],
|
|
|
|
c: 11,
|
|
|
|
};
|
|
|
|
|
2019-05-03 07:50:29 +00:00
|
|
|
let bytes = vec![42, 0, 8, 0, 0, 0, 11, 0, 0, 1, 2, 3];
|
|
|
|
|
2019-09-30 03:58:45 +00:00
|
|
|
assert_eq!(my_foo.as_ssz_bytes(), bytes);
|
2019-05-03 07:50:29 +00:00
|
|
|
|
|
|
|
let decoded_foo = Foo::from_ssz_bytes(&bytes).unwrap();
|
|
|
|
|
2019-09-30 03:58:45 +00:00
|
|
|
assert_eq!(my_foo, decoded_foo);
|
2019-05-03 07:39:51 +00:00
|
|
|
}
|