Skip to main content

reth_trie/
cursor_position.rs

1//! Logical positions shared by trie and hashed overlay cursors.
2
3use std::{fmt::Debug, ops::Bound};
4
5/// The latest logical result and the lower bound of requests that can reuse the cursor positions.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub(crate) enum CursorPosition<K> {
8    /// No seek has been made since construction or reset.
9    Unseeked,
10    /// A seek or advance returned an entry, possibly beyond the requested lower bound.
11    Positioned { key: K, lower_bound: Bound<K> },
12    /// A seek missed or iteration ended, but the scanned range remains reusable.
13    NoCurrent { lower_bound: Bound<K> },
14}
15
16impl<K: Copy + Ord + Debug> CursorPosition<K> {
17    /// Returns the key of the latest logical result, if any.
18    pub(crate) const fn key(&self) -> Option<K> {
19        match self {
20            Self::Positioned { key, .. } => Some(*key),
21            Self::Unseeked | Self::NoCurrent { .. } => None,
22        }
23    }
24
25    /// Returns the reusable request bound, or unbounded before the first seek.
26    const fn lower_bound(&self) -> Bound<K> {
27        match self {
28            Self::Unseeked => Bound::Unbounded,
29            Self::Positioned { lower_bound, .. } | Self::NoCurrent { lower_bound } => *lower_bound,
30        }
31    }
32
33    /// Begins a seek or advance without discarding the previous result's ordering check.
34    pub(crate) const fn set_lower_bound(&mut self, lower_bound: Bound<K>) {
35        *self = match self.key() {
36            Some(key) => Self::Positioned { key, lower_bound },
37            None => Self::NoCurrent { lower_bound },
38        };
39    }
40
41    /// Records the result of a seek or advance while retaining its reusable request bound.
42    pub(crate) fn set_key(&mut self, key: Option<K>) {
43        debug_assert!(
44            self.key().is_none_or(|last| key.is_none_or(|next| next >= last)),
45            "Cannot return entry {:?} previous to the last returned entry at {:?}",
46            key,
47            self.key(),
48        );
49        let lower_bound = self.lower_bound();
50        *self = match key {
51            Some(key) => Self::Positioned { key, lower_bound },
52            None => Self::NoCurrent { lower_bound },
53        };
54    }
55
56    /// Whether a request precedes the range covered by the current cursor positions.
57    pub(crate) fn must_rewind(&self, key: K) -> bool {
58        match self.lower_bound() {
59            Bound::Included(lower) => key < lower,
60            Bound::Excluded(lower) => key <= lower,
61            Bound::Unbounded => false,
62        }
63    }
64}