From 009d05cafd12575d7112c39938ff9b46df729f34 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 7 May 2019 18:42:41 +1000 Subject: [PATCH] Implement basic FixedLenVec --- eth2/types/Cargo.toml | 1 + eth2/types/src/beacon_state.rs | 1 + eth2/types/src/beacon_state/fixed_params.rs | 72 +++++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 eth2/types/src/beacon_state/fixed_params.rs diff --git a/eth2/types/Cargo.toml b/eth2/types/Cargo.toml index 36e251d7e..a2bd08d61 100644 --- a/eth2/types/Cargo.toml +++ b/eth2/types/Cargo.toml @@ -29,6 +29,7 @@ swap_or_not_shuffle = { path = "../utils/swap_or_not_shuffle" } test_random_derive = { path = "../utils/test_random_derive" } tree_hash = { path = "../utils/tree_hash" } tree_hash_derive = { path = "../utils/tree_hash_derive" } +typenum = "1.10" libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "b3c32d9a821ae6cc89079499cc6e8a6bab0bffc3" } [dev-dependencies] diff --git a/eth2/types/src/beacon_state.rs b/eth2/types/src/beacon_state.rs index e9b052f99..29c9d9b31 100644 --- a/eth2/types/src/beacon_state.rs +++ b/eth2/types/src/beacon_state.rs @@ -13,6 +13,7 @@ use tree_hash::TreeHash; use tree_hash_derive::{CachedTreeHash, TreeHash}; mod epoch_cache; +mod fixed_params; mod pubkey_cache; mod tests; diff --git a/eth2/types/src/beacon_state/fixed_params.rs b/eth2/types/src/beacon_state/fixed_params.rs new file mode 100644 index 000000000..08aa675cf --- /dev/null +++ b/eth2/types/src/beacon_state/fixed_params.rs @@ -0,0 +1,72 @@ +use std::borrow::{Borrow, BorrowMut}; +use std::marker::PhantomData; +use std::ops::{Deref, Index, IndexMut}; +use std::slice::SliceIndex; +use typenum::Unsigned; + +pub struct FixedLenVec +where + N: Unsigned, +{ + vec: Vec, + _phantom: PhantomData, +} + +impl From> for FixedLenVec { + fn from(mut vec: Vec) -> Self { + vec.resize_with(Self::capacity(), Default::default); + + Self { + vec, + _phantom: PhantomData, + } + } +} + +impl FixedLenVec { + pub fn capacity() -> usize { + N::to_usize() + } +} + +impl> Index for FixedLenVec { + type Output = I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + Index::index(&self.vec, index) + } +} + +impl> IndexMut for FixedLenVec { + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + IndexMut::index_mut(&mut self.vec, index) + } +} + +#[cfg(test)] +mod test { + use super::*; + use typenum::U8192; + + #[test] + fn slice_ops() { + let vec = vec![1, 2]; + + let mut fixed: FixedLenVec = vec.clone().into(); + + assert_eq!(fixed[0], 1); + assert_eq!(&fixed[0..1], &vec[0..1]); + assert_eq!(&fixed[..], &vec[..]); + + fixed[1] = 3; + assert_eq!(fixed[1], 3); + } +} + +/* +pub trait FixedParams { + type LatestCrosslinks: +} +*/