ssz/lib.rs
1//! Provides encoding (serialization) and decoding (deserialization) in the SimpleSerialize (SSZ)
2//! format designed for use in Ethereum 2.0.
3//!
4//! Adheres to the Ethereum 2.0 [SSZ
5//! specification](https://github.com/ethereum/eth2.0-specs/blob/v0.12.1/ssz/simple-serialize.md)
6//! at v0.12.1.
7//!
8//! ## Example
9//!
10//! ```rust
11//! use ssz_derive::{Encode, Decode};
12//! use ssz::{Decode, Encode};
13//!
14//! #[derive(PartialEq, Debug, Encode, Decode)]
15//! struct Foo {
16//! a: u64,
17//! b: Vec<u16>,
18//! }
19//!
20//! fn ssz_encode_decode_example() {
21//! let foo = Foo {
22//! a: 42,
23//! b: vec![1, 3, 3, 7]
24//! };
25//!
26//! let ssz_bytes: Vec<u8> = foo.as_ssz_bytes();
27//!
28//! let decoded_foo = Foo::from_ssz_bytes(&ssz_bytes).unwrap();
29//!
30//! assert_eq!(foo, decoded_foo);
31//! }
32//!
33//! ```
34//!
35//! See `examples/` for manual implementations of the `Encode` and `Decode` traits.
36
37mod decode;
38mod encode;
39pub mod legacy;
40mod union_selector;
41
42pub use decode::{
43 impls::decode_list_of_variable_length_items, read_offset, split_union_bytes, Decode,
44 DecodeError, SszDecoder, SszDecoderBuilder,
45};
46pub use encode::{encode_length, Encode, SszEncoder};
47pub use union_selector::UnionSelector;
48
49/// The number of bytes used to represent an offset.
50pub const BYTES_PER_LENGTH_OFFSET: usize = 4;
51/// The maximum value that can be represented using `BYTES_PER_LENGTH_OFFSET`.
52#[cfg(target_pointer_width = "32")]
53pub const MAX_LENGTH_VALUE: usize = (std::u32::MAX >> (8 * (4 - BYTES_PER_LENGTH_OFFSET))) as usize;
54#[cfg(target_pointer_width = "64")]
55pub const MAX_LENGTH_VALUE: usize = (std::u64::MAX >> (8 * (8 - BYTES_PER_LENGTH_OFFSET))) as usize;
56
57/// The number of bytes used to indicate the variant of a union.
58pub const BYTES_PER_UNION_SELECTOR: usize = 1;
59/// The highest possible union selector value (higher values are reserved for backwards compatible
60/// extensions).
61pub const MAX_UNION_SELECTOR: u8 = 127;
62
63/// Convenience function to SSZ encode an object supporting ssz::Encode.
64///
65/// Equivalent to `val.as_ssz_bytes()`.
66pub fn ssz_encode<T>(val: &T) -> Vec<u8>
67where
68 T: Encode,
69{
70 val.as_ssz_bytes()
71}