Skip to content

Commit

Permalink
feat: add trie root fns for exact sized iter
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Dec 11, 2024
1 parent 9d3fdba commit ba39420
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,38 +15,57 @@ pub const fn adjust_index_for_rlp(i: usize, len: usize) -> usize {
}
}

/// Compute a trie root of the iterator of rlp encodable items.
pub fn ordered_trie_root_iter<'a, I, T>(items: I) -> B256
where
I: ExactSizeIterator<Item = &'a T>,
T: Encodable +'a,
{
ordered_trie_root_with_encoder_iter(items, |item, buf| item.encode(buf))
}

/// Compute a trie root of the collection of rlp encodable items.
pub fn ordered_trie_root<T: Encodable>(items: &[T]) -> B256 {
ordered_trie_root_with_encoder(items, |item, buf| item.encode(buf))
}

/// Compute a trie root of the collection of items with a custom encoder.
pub fn ordered_trie_root_with_encoder<T, F>(items: &[T], mut encode: F) -> B256
/// Compute a trie root of the given iterator of items with a custom encoder.
pub fn ordered_trie_root_with_encoder_iter<'a, I, T, F>(items: I, mut encode: F) -> B256
where
I: ExactSizeIterator<Item = &'a T>,
T:'a,
F: FnMut(&T, &mut Vec<u8>),
{
if items.is_empty() {
let items_len = items.len();
if items_len == 0 {
return EMPTY_ROOT_HASH;
}

let mut value_buffer = Vec::new();

let mut hb = HashBuilder::default();
let items_len = items.len();
for i in 0..items_len {
for (i, item) in items.enumerate() {
let index = adjust_index_for_rlp(i, items_len);

let index_buffer = alloy_rlp::encode_fixed_size(&index);

value_buffer.clear();
encode(&items[index], &mut value_buffer);
encode(item, &mut value_buffer);

hb.add_leaf(Nibbles::unpack(&index_buffer), &value_buffer);
}

hb.root()
}

/// Compute a trie root of the collection of items with a custom encoder.
pub fn ordered_trie_root_with_encoder<T, F>(items: &[T], mut encode: F) -> B256
where
F: FnMut(&T, &mut Vec<u8>),
{
ordered_trie_root_with_encoder_iter(items.iter(), |item, buf| encode(item, buf))
}

/// Ethereum specific trie root functions.
#[cfg(feature = "ethereum")]
pub use ethereum::*;
Expand Down

0 comments on commit ba39420

Please sign in to comment.