Skip to content

Commit

Permalink
Implements DoubleEndedIterator for trie iterators (#208)
Browse files Browse the repository at this point in the history
* double ended iterator implementation
  • Loading branch information
snowmead authored Jan 5, 2024
1 parent d3e6377 commit 2edd0a1
Show file tree
Hide file tree
Showing 10 changed files with 934 additions and 121 deletions.
64 changes: 63 additions & 1 deletion trie-db/src/fatdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::{
};
use hash_db::{HashDBRef, Hasher};

use crate::{rstd::boxed::Box, MerkleValue, TrieDBBuilder};
use crate::{rstd::boxed::Box, triedb::TrieDBDoubleEndedIterator, MerkleValue, TrieDBBuilder};

/// A `Trie` implementation which hashes keys and uses a generic `HashDB` backing database.
/// Additionaly it stores inserted hash-key mappings for later retrieval.
Expand Down Expand Up @@ -109,6 +109,22 @@ where
trie: &'db TrieDB<'db, 'cache, L>,
}

/// Double ended iterator over inserted pairs of key values.
pub struct FatDBDoubleEndedIterator<'db, 'cache, L>
where
L: TrieLayout,
{
trie_iterator: TrieDBDoubleEndedIterator<'db, 'cache, L>,
trie: &'db TrieDB<'db, 'cache, L>,
}

impl<'a, 'cache, L: TrieLayout> FatDBDoubleEndedIterator<'a, 'cache, L> {
/// Create a new double ended iterator.
pub fn new(db: &'a TrieDB<'a, 'cache, L>) -> Result<Self, TrieHash<L>, CError<L>> {
Ok(Self { trie_iterator: TrieDBDoubleEndedIterator::new(db)?, trie: db })
}
}

impl<'db, 'cache, L> FatDBIterator<'db, 'cache, L>
where
L: TrieLayout,
Expand Down Expand Up @@ -148,6 +164,52 @@ where
}
}

impl<'db, 'cache, L> TrieIterator<L> for FatDBDoubleEndedIterator<'db, 'cache, L>
where
L: TrieLayout,
{
fn seek(&mut self, key: &[u8]) -> Result<(), TrieHash<L>, CError<L>> {
let hashed_key = L::Hash::hash(key);
self.trie_iterator.seek(hashed_key.as_ref())
}
}

impl<'db, 'cache, L> Iterator for FatDBDoubleEndedIterator<'db, 'cache, L>
where
L: TrieLayout,
{
type Item = TrieItem<TrieHash<L>, CError<L>>;

fn next(&mut self) -> Option<Self::Item> {
self.trie_iterator.next().map(|res| {
res.map(|(hash, value)| {
let aux_hash = L::Hash::hash(&hash);
(
self.trie.db().get(&aux_hash, Default::default()).expect("Missing fatdb hash"),
value,
)
})
})
}
}

impl<'db, 'cache, L> DoubleEndedIterator for FatDBDoubleEndedIterator<'db, 'cache, L>
where
L: TrieLayout,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.trie_iterator.next_back().map(|res| {
res.map(|(hash, value)| {
let aux_hash = L::Hash::hash(&hash);
(
self.trie.db().get(&aux_hash, Default::default()).expect("Missing fatdb hash"),
value,
)
})
})
}
}

/// Iterator over inserted keys.
pub struct FatDBKeyIterator<'db, 'cache, L>
where
Expand Down
Loading

0 comments on commit 2edd0a1

Please sign in to comment.