Last active
May 7, 2019 06:39
-
-
Save michaelsproul/2c8e0d68617c736352ce9f4055cb295b to your computer and use it in GitHub Desktop.
Experiments with generic-array and BeaconState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use generic_array::*; | |
| use std::marker::PhantomData; | |
| use typenum::Unsigned; | |
| use typenum::{U1024, U4096, U512, U8192}; | |
| type Hash = [u8; 32]; | |
| type Crosslink = u64; | |
| trait FixedArray<T> { | |
| // Not using `std::Default` for brevity. | |
| fn default() -> Self; | |
| // Bogus method for demonstration. | |
| fn num_elems(&self) -> usize; | |
| } | |
| impl<T: Default, N> FixedArray<T> for GenericArray<T, N> | |
| where | |
| N: ArrayLength<T>, | |
| { | |
| fn default() -> Self { | |
| <Self as Default>::default() | |
| } | |
| fn num_elems(&self) -> usize { | |
| N::to_usize() | |
| } | |
| } | |
| struct GenericBundle<R, C> { | |
| _nightmares: PhantomData<(R, C)>, | |
| } | |
| trait Bundle { | |
| type RandaoMixesArray: FixedArray<Hash>; | |
| type CrosslinkArray: FixedArray<Crosslink>; | |
| } | |
| impl<R, C> Bundle for GenericBundle<R, C> | |
| where | |
| R: ArrayLength<Hash>, | |
| C: ArrayLength<Crosslink>, | |
| { | |
| type RandaoMixesArray = GenericArray<Hash, R>; | |
| type CrosslinkArray = GenericArray<Crosslink, C>; | |
| } | |
| type BigBundle = GenericBundle<U8192, U1024>; | |
| type SmallBundle = GenericBundle<U4096, U512>; | |
| struct BeaconState<T: Bundle> { | |
| slot: u64, | |
| lastest_randao_mixes: Box<T::RandaoMixesArray>, | |
| current_crosslinks: Box<T::CrosslinkArray>, | |
| } | |
| type BigBoiState = BeaconState<BigBundle>; | |
| type SmallBoiState = BeaconState<SmallBundle>; | |
| impl<T: Bundle> BeaconState<T> { | |
| pub fn genesis() -> Self { | |
| Self { | |
| slot: 0, | |
| lastest_randao_mixes: Box::new(T::RandaoMixesArray::default()), | |
| current_crosslinks: Box::new(T::CrosslinkArray::default()), | |
| } | |
| } | |
| } | |
| fn print_slot<T: Bundle>(state: &BeaconState<T>) { | |
| println!( | |
| "num randao: {}, num_crosslinks: {}", | |
| state.lastest_randao_mixes.num_elems(), | |
| state.current_crosslinks.num_elems() | |
| ) | |
| } | |
| fn main() { | |
| let nr = 8192; | |
| if nr == 4096 { | |
| let state = SmallBoiState::genesis(); | |
| print_slot(&state); | |
| } else { | |
| let state = BigBoiState::genesis(); | |
| print_slot(&state); | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment