Struct ssz_types::Bitfield

source ·
pub struct Bitfield<T> { /* private fields */ }
Expand description

A heap-allocated, ordered, fixed-length, collection of bool values. Use of BitList or BitVector type aliases is preferred over direct use of this struct.

The T type parameter is used to define length behaviour with the Variable or Fixed marker structs.

The length of the Bitfield is set at instantiation (i.e., runtime, not compile time). However, use with a Variable sets a type-level (i.e., compile-time) maximum length and Fixed provides a type-level fixed length.

Example

The example uses the following crate-level type aliases:

  • BitList<N> is an alias for Bitfield<Variable<N>>
  • BitVector<N> is an alias for Bitfield<Fixed<N>>
use ssz_types::{BitVector, BitList, typenum};

// `BitList` has a type-level maximum length. The length of the list is specified at runtime
// and it must be less than or equal to `N`. After instantiation, `BitList` cannot grow or
// shrink.
type BitList8 = BitList<typenum::U8>;

// Creating a `BitList` with a larger-than-`N` capacity returns `None`.
assert!(BitList8::with_capacity(9).is_err());

let mut bitlist = BitList8::with_capacity(4).unwrap();  // `BitList` permits a capacity of less than the maximum.
assert!(bitlist.set(3, true).is_ok());  // Setting inside the instantiation capacity is permitted.
assert!(bitlist.set(5, true).is_err());  // Setting outside that capacity is not.

// `BitVector` has a type-level fixed length. Unlike `BitList`, it cannot be instantiated with a custom length
// or grow/shrink.
type BitVector8 = BitVector<typenum::U8>;

let mut bitvector = BitVector8::new();
assert_eq!(bitvector.len(), 8); // `BitVector` length is fixed at the type-level.
assert!(bitvector.set(7, true).is_ok());  // Setting inside the capacity is permitted.
assert!(bitvector.set(9, true).is_err());  // Setting outside the capacity is not.

Note

The internal representation of the bitfield is the same as that required by SSZ. The lowest byte (by Vec index) stores the lowest bit-indices and the right-most bit stores the lowest bit-index. E.g., smallvec![0b0000_0001, 0b0000_0010] has bits 0, 9 set.

Implementations§

source§

impl<N: Unsigned + Clone> Bitfield<Variable<N>>

source

pub fn with_capacity(num_bits: usize) -> Result<Self, Error>

Instantiate with capacity for num_bits boolean values. The length cannot be grown or shrunk after instantiation.

All bits are initialized to false.

Returns None if num_bits > N.

source

pub fn max_len() -> usize

Equal to N regardless of the value supplied to with_capacity.

source

pub fn into_bytes(self) -> SmallVec<[u8; 32]>

Consumes self, returning a serialized representation.

The output is faithful to the SSZ encoding of self, such that a leading true bit is used to indicate the length of the bitfield.

Example
use ssz_types::{BitList, typenum};
use smallvec::SmallVec;

type BitList8 = BitList<typenum::U8>;

let b = BitList8::with_capacity(4).unwrap();

assert_eq!(b.into_bytes(), SmallVec::from_buf([0b0001_0000]));
source

pub fn from_bytes(bytes: SmallVec<[u8; 32]>) -> Result<Self, Error>

Instantiates a new instance from bytes. Consumes the same format that self.into_bytes() produces (SSZ).

Returns None if bytes are not a valid encoding.

source

pub fn intersection(&self, other: &Self) -> Self

Compute the intersection of two BitLists of potentially different lengths.

Return a new BitList with length equal to the shorter of the two inputs.

source

pub fn union(&self, other: &Self) -> Self

Compute the union of two BitLists of potentially different lengths.

Return a new BitList with length equal to the longer of the two inputs.

source

pub fn is_subset(&self, other: &Self) -> bool

Returns true if self is a subset of other and false otherwise.

source§

impl<N: Unsigned + Clone> Bitfield<Fixed<N>>

source

pub fn new() -> Self

Instantiate a new Bitfield with a fixed-length of N bits.

All bits are initialized to false.

source

pub fn capacity() -> usize

Returns N, the number of bits in Self.

source

pub fn into_bytes(self) -> SmallVec<[u8; 32]>

Consumes self, returning a serialized representation.

The output is faithful to the SSZ encoding of self.

Example
use ssz_types::{BitVector, typenum};
use smallvec::SmallVec;

type BitVector4 = BitVector<typenum::U4>;

assert_eq!(BitVector4::new().into_bytes(), SmallVec::from_buf([0b0000_0000]));
source

pub fn from_bytes(bytes: SmallVec<[u8; 32]>) -> Result<Self, Error>

Instantiates a new instance from bytes. Consumes the same format that self.into_bytes() produces (SSZ).

Returns None if bytes are not a valid encoding.

source

pub fn intersection(&self, other: &Self) -> Self

Compute the intersection of two fixed-length Bitfields.

Return a new fixed-length Bitfield.

source

pub fn union(&self, other: &Self) -> Self

Compute the union of two fixed-length Bitfields.

Return a new fixed-length Bitfield.

source

pub fn is_subset(&self, other: &Self) -> bool

Returns true if self is a subset of other and false otherwise.

source§

impl<T: BitfieldBehaviour> Bitfield<T>

source

pub fn set(&mut self, i: usize, value: bool) -> Result<(), Error>

Sets the i’th bit to value.

Returns None if i is out-of-bounds of self.

source

pub fn get(&self, i: usize) -> Result<bool, Error>

Returns the value of the i’th bit.

Returns Error if i is out-of-bounds of self.

source

pub fn len(&self) -> usize

Returns the number of bits stored in self.

source

pub fn is_empty(&self) -> bool

Returns true if self.len() == 0.

source

pub fn into_raw_bytes(self) -> SmallVec<[u8; 32]>

Returns the underlying bytes representation of the bitfield.

source

pub fn as_slice(&self) -> &[u8]

Returns a view into the underlying bytes representation of the bitfield.

source

pub fn highest_set_bit(&self) -> Option<usize>

Returns the Some(i) where i is the highest index with a set bit. Returns None if there are no set bits.

source

pub fn iter(&self) -> BitIter<'_, T>

Returns an iterator across bitfield bool values, starting at the lowest index.

source

pub fn is_zero(&self) -> bool

Returns true if no bits are set.

source

pub fn num_set_bits(&self) -> usize

Returns the number of bits that are set to true.

source

pub fn difference(&self, other: &Self) -> Self

Compute the difference of this Bitfield and another of potentially different length.

source

pub fn difference_inplace(&mut self, other: &Self)

Compute the difference of this Bitfield and another of potentially different length.

source

pub fn shift_up(&mut self, n: usize) -> Result<(), Error>

Shift the bits to higher indices, filling the lower indices with zeroes.

The amount to shift by, n, must be less than or equal to self.len().

Trait Implementations§

source§

impl<T: Clone> Clone for Bitfield<T>

source§

fn clone(&self) -> Bitfield<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug> Debug for Bitfield<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<N: Unsigned + Clone> Decode for Bitfield<Fixed<N>>

source§

fn is_ssz_fixed_len() -> bool

Returns true if this object has a fixed-length. Read more
source§

fn ssz_fixed_len() -> usize

The number of bytes this object occupies in the fixed-length portion of the SSZ bytes. Read more
source§

fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError>

Attempts to decode Self from bytes, returning a DecodeError on failure. Read more
source§

impl<N: Unsigned + Clone> Decode for Bitfield<Variable<N>>

source§

fn is_ssz_fixed_len() -> bool

Returns true if this object has a fixed-length. Read more
source§

fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError>

Attempts to decode Self from bytes, returning a DecodeError on failure. Read more
source§

fn ssz_fixed_len() -> usize

The number of bytes this object occupies in the fixed-length portion of the SSZ bytes. Read more
source§

impl<N: Unsigned + Clone> Default for Bitfield<Fixed<N>>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'de, N: Unsigned + Clone> Deserialize<'de> for Bitfield<Fixed<N>>

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Serde serialization is compliant with the Ethereum YAML test format.

source§

impl<'de, N: Unsigned + Clone> Deserialize<'de> for Bitfield<Variable<N>>

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Serde serialization is compliant with the Ethereum YAML test format.

source§

impl<N: Unsigned + Clone> Encode for Bitfield<Fixed<N>>

source§

fn is_ssz_fixed_len() -> bool

Returns true if this object has a fixed-length. Read more
source§

fn ssz_bytes_len(&self) -> usize

Returns the size (in bytes) when self is serialized. Read more
source§

fn ssz_fixed_len() -> usize

The number of bytes this object occupies in the fixed-length portion of the SSZ bytes. Read more
source§

fn ssz_append(&self, buf: &mut Vec<u8>)

Append the encoding self to buf. Read more
source§

fn as_ssz_bytes(&self) -> Vec<u8>

Returns the full-form encoding of this object. Read more
source§

impl<N: Unsigned + Clone> Encode for Bitfield<Variable<N>>

source§

fn is_ssz_fixed_len() -> bool

Returns true if this object has a fixed-length. Read more
source§

fn ssz_bytes_len(&self) -> usize

Returns the size (in bytes) when self is serialized. Read more
source§

fn ssz_append(&self, buf: &mut Vec<u8>)

Append the encoding self to buf. Read more
source§

fn ssz_fixed_len() -> usize

The number of bytes this object occupies in the fixed-length portion of the SSZ bytes. Read more
source§

fn as_ssz_bytes(&self) -> Vec<u8>

Returns the full-form encoding of this object. Read more
source§

impl<T> Hash for Bitfield<T>

source§

fn hash<__HT>(&self, __state: &mut __HT)
where __HT: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<T> PartialEq for Bitfield<T>

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<N: Unsigned + Clone> Serialize for Bitfield<Fixed<N>>

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serde serialization is compliant with the Ethereum YAML test format.

source§

impl<N: Unsigned + Clone> Serialize for Bitfield<Variable<N>>

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serde serialization is compliant with the Ethereum YAML test format.

source§

impl<N: Unsigned + Clone> TreeHash for Bitfield<Fixed<N>>

source§

impl<N: Unsigned + Clone> TreeHash for Bitfield<Variable<N>>

source§

impl<T> Eq for Bitfield<T>

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for Bitfield<T>
where T: RefUnwindSafe,

§

impl<T> Send for Bitfield<T>
where T: Send,

§

impl<T> Sync for Bitfield<T>
where T: Sync,

§

impl<T> Unpin for Bitfield<T>
where T: Unpin,

§

impl<T> UnwindSafe for Bitfield<T>
where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,