ssz_types/
lib.rs

1//! Provides types with unique properties required for SSZ serialization and Merklization:
2//!
3//! - `FixedVector`: A heap-allocated list with a size that is fixed at compile time.
4//! - `VariableList`: A heap-allocated list that cannot grow past a type-level maximum length.
5//! - `BitList`: A heap-allocated bitfield that with a type-level _maximum_ length.
6//! - `BitVector`: A heap-allocated bitfield that with a type-level _fixed__ length.
7//!
8//! These structs are required as SSZ serialization and Merklization rely upon type-level lengths
9//! for padding and verification.
10//!
11//! Adheres to the Ethereum 2.0 [SSZ
12//! specification](https://github.com/ethereum/eth2.0-specs/blob/v0.12.1/ssz/simple-serialize.md)
13//! at v0.12.1.
14//!
15//! ## Example
16//! ```
17//! use ssz_types::*;
18//!
19//! pub struct Example {
20//!     bit_vector: BitVector<typenum::U8>,
21//!     bit_list: BitList<typenum::U8>,
22//!     variable_list: VariableList<u64, typenum::U8>,
23//!     fixed_vector: FixedVector<u64, typenum::U8>,
24//! }
25//!
26//! let mut example = Example {
27//!     bit_vector: Bitfield::new(),
28//!     bit_list: Bitfield::with_capacity(4).unwrap(),
29//!     variable_list: <_>::from(vec![0, 1]),
30//!     fixed_vector: <_>::from(vec![2, 3]),
31//! };
32//!
33//! assert_eq!(example.bit_vector.len(), 8);
34//! assert_eq!(example.bit_list.len(), 4);
35//! assert_eq!(&example.variable_list[..], &[0, 1]);
36//! assert_eq!(&example.fixed_vector[..], &[2, 3, 0, 0, 0, 0, 0, 0]);
37//!
38//! ```
39
40#[macro_use]
41mod bitfield;
42mod fixed_vector;
43pub mod serde_utils;
44mod tree_hash;
45mod variable_list;
46
47pub use bitfield::{BitList, BitVector, Bitfield};
48pub use fixed_vector::FixedVector;
49pub use typenum;
50pub use variable_list::VariableList;
51
52pub mod length {
53    pub use crate::bitfield::{Fixed, Variable};
54}
55
56/// Returned when an item encounters an error.
57#[derive(PartialEq, Debug, Clone)]
58pub enum Error {
59    OutOfBounds {
60        i: usize,
61        len: usize,
62    },
63    /// A `BitList` does not have a set bit, therefore it's length is unknowable.
64    MissingLengthInformation,
65    /// A `BitList` has excess bits set to true.
66    ExcessBits,
67    /// A `BitList` has an invalid number of bytes for a given bit length.
68    InvalidByteCount {
69        given: usize,
70        expected: usize,
71    },
72}