Implement basic FixedLenVec
This commit is contained in:
parent
00f85a0324
commit
009d05cafd
@ -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]
|
||||
|
@ -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;
|
||||
|
||||
|
72
eth2/types/src/beacon_state/fixed_params.rs
Normal file
72
eth2/types/src/beacon_state/fixed_params.rs
Normal file
@ -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<T, N>
|
||||
where
|
||||
N: Unsigned,
|
||||
{
|
||||
vec: Vec<T>,
|
||||
_phantom: PhantomData<N>,
|
||||
}
|
||||
|
||||
impl<T: Default, N: Unsigned> From<Vec<T>> for FixedLenVec<T, N> {
|
||||
fn from(mut vec: Vec<T>) -> Self {
|
||||
vec.resize_with(Self::capacity(), Default::default);
|
||||
|
||||
Self {
|
||||
vec,
|
||||
_phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, N: Unsigned> FixedLenVec<T, N> {
|
||||
pub fn capacity() -> usize {
|
||||
N::to_usize()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, N: Unsigned, I: SliceIndex<[T]>> Index<I> for FixedLenVec<T, N> {
|
||||
type Output = I::Output;
|
||||
|
||||
#[inline]
|
||||
fn index(&self, index: I) -> &Self::Output {
|
||||
Index::index(&self.vec, index)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, N: Unsigned, I: SliceIndex<[T]>> IndexMut<I> for FixedLenVec<T, N> {
|
||||
#[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<u64, U8192> = 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:
|
||||
}
|
||||
*/
|
Loading…
Reference in New Issue
Block a user