reth_trie/
forward_cursor.rs1#[derive(Debug)]
5pub struct ForwardInMemoryCursor<'a, K, V> {
6 entries: &'a [(K, V)],
8 idx: usize,
10}
11
12impl<'a, K, V> ForwardInMemoryCursor<'a, K, V> {
13 #[inline]
17 pub const fn new(entries: &'a [(K, V)]) -> Self {
18 Self { entries, idx: 0 }
19 }
20
21 #[inline]
23 pub const fn is_empty(&self) -> bool {
24 self.entries.is_empty()
25 }
26
27 #[inline]
29 pub fn has_any<F>(&self, predicate: F) -> bool
30 where
31 F: Fn(&(K, V)) -> bool,
32 {
33 self.entries.iter().any(predicate)
34 }
35
36 #[inline]
38 pub fn current(&self) -> Option<&(K, V)> {
39 self.entries.get(self.idx)
40 }
41
42 #[inline]
44 pub const fn reset(&mut self) {
45 self.idx = 0;
46 }
47
48 #[inline]
49 fn next(&mut self) -> Option<&(K, V)> {
50 let entry = self.entries.get(self.idx)?;
51 self.idx += 1;
52 Some(entry)
53 }
54}
55
56impl<K, V> ForwardInMemoryCursor<'_, K, V>
57where
58 K: PartialOrd + Clone,
59 V: Clone,
60{
61 pub fn seek(&mut self, key: &K) -> Option<(K, V)> {
64 self.advance_while(|k| k < key)
65 }
66
67 pub fn first_after(&mut self, key: &K) -> Option<(K, V)> {
70 self.advance_while(|k| k <= key)
71 }
72
73 fn advance_while(&mut self, predicate: impl Fn(&K) -> bool) -> Option<(K, V)> {
79 let mut entry;
80 loop {
81 entry = self.current();
82 if entry.is_some_and(|(k, _)| predicate(k)) {
83 self.next();
84 } else {
85 break;
86 }
87 }
88 entry.cloned()
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn test_cursor() {
98 let mut cursor = ForwardInMemoryCursor::new(&[(1, ()), (2, ()), (3, ()), (4, ()), (5, ())]);
99 assert_eq!(cursor.current(), Some(&(1, ())));
100
101 assert_eq!(cursor.seek(&0), Some((1, ())));
102 assert_eq!(cursor.current(), Some(&(1, ())));
103
104 assert_eq!(cursor.seek(&3), Some((3, ())));
105 assert_eq!(cursor.current(), Some(&(3, ())));
106
107 assert_eq!(cursor.seek(&3), Some((3, ())));
108 assert_eq!(cursor.current(), Some(&(3, ())));
109
110 assert_eq!(cursor.seek(&4), Some((4, ())));
111 assert_eq!(cursor.current(), Some(&(4, ())));
112
113 assert_eq!(cursor.seek(&6), None);
114 assert_eq!(cursor.current(), None);
115 }
116}