lighthouse-pulse/eth2/utils/cached_tree_hash/src/impls.rs

108 lines
3.0 KiB
Rust
Raw Normal View History

use super::*;
2019-04-25 23:55:03 +00:00
use crate::merkleize::merkleize;
use ethereum_types::H256;
pub mod vec;
2019-04-15 02:01:12 +00:00
macro_rules! impl_for_single_leaf_int {
($type: ident) => {
impl CachedTreeHash<$type> for $type {
fn new_tree_hash_cache(&self, _depth: usize) -> Result<TreeHashCache, Error> {
Ok(TreeHashCache::from_bytes(
merkleize(self.to_le_bytes().to_vec()),
false,
None,
)?)
}
fn tree_hash_cache_schema(&self, depth: usize) -> BTreeSchema {
BTreeSchema::from_lengths(depth, vec![1])
}
fn update_tree_hash_cache(&self, cache: &mut TreeHashCache) -> Result<(), Error> {
let leaf = merkleize(self.to_le_bytes().to_vec());
cache.maybe_update_chunk(cache.chunk_index, &leaf)?;
cache.chunk_index += 1;
Ok(())
}
}
};
}
impl_for_single_leaf_int!(u8);
impl_for_single_leaf_int!(u16);
impl_for_single_leaf_int!(u32);
impl_for_single_leaf_int!(u64);
impl_for_single_leaf_int!(usize);
impl CachedTreeHash<bool> for bool {
fn new_tree_hash_cache(&self, _depth: usize) -> Result<TreeHashCache, Error> {
Ok(TreeHashCache::from_bytes(
merkleize((*self as u8).to_le_bytes().to_vec()),
false,
None,
)?)
}
fn tree_hash_cache_schema(&self, depth: usize) -> BTreeSchema {
BTreeSchema::from_lengths(depth, vec![1])
}
fn update_tree_hash_cache(&self, cache: &mut TreeHashCache) -> Result<(), Error> {
let leaf = merkleize((*self as u8).to_le_bytes().to_vec());
cache.maybe_update_chunk(cache.chunk_index, &leaf)?;
cache.chunk_index += 1;
Ok(())
}
}
impl CachedTreeHash<[u8; 4]> for [u8; 4] {
2019-04-24 08:13:37 +00:00
fn new_tree_hash_cache(&self, _depth: usize) -> Result<TreeHashCache, Error> {
2019-04-13 03:18:18 +00:00
Ok(TreeHashCache::from_bytes(
merkleize(self.to_vec()),
2019-04-13 03:18:18 +00:00
false,
2019-04-23 23:29:32 +00:00
None,
2019-04-13 03:18:18 +00:00
)?)
}
fn tree_hash_cache_schema(&self, depth: usize) -> BTreeSchema {
BTreeSchema::from_lengths(depth, vec![1])
2019-04-24 08:13:37 +00:00
}
fn update_tree_hash_cache(&self, cache: &mut TreeHashCache) -> Result<(), Error> {
let leaf = merkleize(self.to_vec());
2019-04-24 08:13:37 +00:00
cache.maybe_update_chunk(cache.chunk_index, &leaf)?;
cache.chunk_index += 1;
Ok(())
}
}
impl CachedTreeHash<H256> for H256 {
2019-04-24 08:13:37 +00:00
fn new_tree_hash_cache(&self, _depth: usize) -> Result<TreeHashCache, Error> {
Ok(TreeHashCache::from_bytes(
merkleize(self.as_bytes().to_vec()),
2019-04-24 08:13:37 +00:00
false,
None,
)?)
}
fn tree_hash_cache_schema(&self, depth: usize) -> BTreeSchema {
BTreeSchema::from_lengths(depth, vec![1])
}
fn update_tree_hash_cache(&self, cache: &mut TreeHashCache) -> Result<(), Error> {
let leaf = merkleize(self.as_bytes().to_vec());
cache.maybe_update_chunk(cache.chunk_index, &leaf)?;
cache.chunk_index += 1;
2019-04-22 11:31:39 +00:00
Ok(())
}
}