Skip to content

Commit

Permalink
integrate forward cursor into hashed post state cursors
Browse files Browse the repository at this point in the history
  • Loading branch information
rkrasiuk committed Jun 25, 2024
1 parent f3eaa7c commit bc1a410
Show file tree
Hide file tree
Showing 2 changed files with 180 additions and 217 deletions.
16 changes: 11 additions & 5 deletions crates/trie/trie/src/forward_cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,38 @@ impl<'a, K, V> ForwardInMemoryCursor<'a, K, V> {
pub const fn new(entries: &'a Vec<(K, V)>) -> Self {
Self { entries, index: 0 }
}

/// Returns `true` if the cursor is empty, regardless of its position.
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}

impl<'a, K, V> ForwardInMemoryCursor<'a, K, V>
where
K: PartialOrd,
K: PartialOrd + Copy,
V: Copy,
{
/// Advances the cursor forward while `comparator` returns `true` or until the collection is
/// exhausted. Returns the first entry for which `comparator` returns `false` or `None`.
fn advance_while(&mut self, comparator: impl Fn(&K) -> bool) -> Option<&(K, V)> {
fn advance_while(&mut self, comparator: impl Fn(&K) -> bool) -> Option<(K, V)> {
let mut entry = self.entries.get(self.index);
while entry.map_or(false, |entry| comparator(&entry.0)) {
self.index += 1;
entry = self.entries.get(self.index);
}
entry
entry.copied()
}

/// Returns the first entry from the current cursor position that's greater or equal to the
/// provided key. This method advances the cursor forward.
pub fn seek(&mut self, key: &K) -> Option<&(K, V)> {
pub fn seek(&mut self, key: &K) -> Option<(K, V)> {
self.advance_while(|k| k < key)
}

/// Returns the first entry from the current cursor position that's greater than the provided
/// key. This method advances the cursor forward.
pub fn first_after(&mut self, key: &K) -> Option<&(K, V)> {
pub fn first_after(&mut self, key: &K) -> Option<(K, V)> {
self.advance_while(|k| k <= key)
}
}
Loading

0 comments on commit bc1a410

Please sign in to comment.