reth_trie/
forward_cursor.rs

1/// The implementation of forward-only in memory cursor over the entries.
2/// The cursor operates under the assumption that the supplied collection is pre-sorted.
3#[derive(Debug)]
4pub struct ForwardInMemoryCursor<'a, K, V> {
5    /// The reference to the pre-sorted collection of entries.
6    entries: &'a Vec<(K, V)>,
7    /// The index where cursor is currently positioned.
8    index: usize,
9}
10
11impl<'a, K, V> ForwardInMemoryCursor<'a, K, V> {
12    /// Create new forward cursor positioned at the beginning of the collection.
13    /// The cursor expects all of the entries have been sorted in advance.
14    pub const fn new(entries: &'a Vec<(K, V)>) -> Self {
15        Self { entries, index: 0 }
16    }
17
18    /// Returns `true` if the cursor is empty, regardless of its position.
19    pub fn is_empty(&self) -> bool {
20        self.entries.is_empty()
21    }
22}
23
24impl<K, V> ForwardInMemoryCursor<'_, K, V>
25where
26    K: PartialOrd + Clone,
27    V: Clone,
28{
29    /// Advances the cursor forward while `comparator` returns `true` or until the collection is
30    /// exhausted. Returns the first entry for which `comparator` returns `false` or `None`.
31    fn advance_while_false(&mut self, comparator: impl Fn(&K) -> bool) -> Option<(K, V)> {
32        let mut entry = self.entries.get(self.index);
33        while entry.is_some_and(|entry| comparator(&entry.0)) {
34            self.index += 1;
35            entry = self.entries.get(self.index);
36        }
37        entry.cloned()
38    }
39
40    /// Returns the first entry from the current cursor position that's greater or equal to the
41    /// provided key. This method advances the cursor forward.
42    pub fn seek(&mut self, key: &K) -> Option<(K, V)> {
43        self.advance_while_false(|k| k < key)
44    }
45
46    /// Returns the first entry from the current cursor position that's greater than the provided
47    /// key. This method advances the cursor forward.
48    pub fn first_after(&mut self, key: &K) -> Option<(K, V)> {
49        self.advance_while_false(|k| k <= key)
50    }
51}