1use super::{
2 branch_child_idx::{BranchChildIdx, BranchChildIter},
3 ArenaSparseNode, ArenaSparseNodeState, BranchChild, ExtensionChild, Index, NodeArena,
4};
5use alloc::vec::Vec;
6use reth_trie_common::Nibbles;
7use tracing::{instrument, trace};
8
9const TRACE_TARGET: &str = "trie::arena::cursor";
10
11#[derive(Debug, Clone)]
16pub(super) struct ArenaCursorStackEntry {
17 pub(super) index: Index,
19 path_len: u8,
22 next_dense_idx: u8,
26}
27
28#[derive(Debug)]
30pub(super) enum SeekResult {
31 EmptyRoot,
33 RevealedLeaf,
35 Blinded,
37 Diverged,
39 NoChild { child_nibble: u8 },
41 RevealedSubtrie,
43}
44
45#[derive(Debug)]
47pub(super) enum NextResult {
48 NonBranch,
51 Branch,
54 Done,
56}
57
58pub(super) fn branch_idx(arena: &NodeArena, idx: Index) -> Option<Index> {
60 match &arena[idx] {
61 ArenaSparseNode::Branch(_) => Some(idx),
62 ArenaSparseNode::Extension { child, .. } => child.revealed_index(),
63 _ => None,
64 }
65}
66
67#[derive(Debug, Default, Clone)]
76pub(super) struct ArenaCursor {
77 stack: Vec<ArenaCursorStackEntry>,
78 path: Nibbles,
86 needs_pop: bool,
89}
90
91impl ArenaCursor {
92 pub(super) fn head(&self) -> Option<&ArenaCursorStackEntry> {
94 self.stack.last()
95 }
96
97 pub(super) fn parent(&self) -> Option<&ArenaCursorStackEntry> {
99 let len = self.stack.len();
100 (len >= 2).then(|| &self.stack[len - 2])
101 }
102
103 pub(super) const fn depth(&self) -> usize {
109 self.stack.len() - 1
110 }
111
112 pub(super) fn head_path(&self) -> Nibbles {
114 self.entry_path(self.head_entry())
115 }
116
117 pub(super) fn head_path_len(&self) -> usize {
120 self.head_entry().path_len as usize
121 }
122
123 pub(super) fn head_last_nibble(&self) -> Option<u8> {
126 self.head_path_len().checked_sub(1).map(|i| self.path.get_unchecked(i))
127 }
128
129 #[instrument(level = "trace", target = TRACE_TARGET, skip(self, arena))]
133 pub(super) fn reset(&mut self, arena: &NodeArena, idx: Index, path: Nibbles) {
134 debug_assert!(
135 self.stack.len() <= 1 && !self.needs_pop,
136 "cursor must be drained before reset; stack has {} entries, needs_pop={}",
137 self.stack.len(),
138 self.needs_pop,
139 );
140 self.stack.clear();
141 self.needs_pop = false;
142 self.path = path;
143 self.push(arena, idx, path.len());
144 }
145
146 fn push(&mut self, arena: &NodeArena, idx: Index, path_len: usize) {
149 debug_assert!(arena.contains_key(idx), "push called with invalid arena index");
150 debug_assert!(
151 path_len <= self.path.len(),
152 "pushed path length {path_len} exceeds cursor path {:?}",
153 self.path,
154 );
155 self.stack.push(ArenaCursorStackEntry {
156 index: idx,
157 path_len: path_len as u8,
158 next_dense_idx: 0,
159 });
160 trace!(
161 target: TRACE_TARGET,
162 ?idx,
163 path = ?self.path.slice_unchecked(0, path_len),
164 "Pushed stack entry",
165 );
166 }
167
168 #[instrument(level = "trace", target = TRACE_TARGET, skip(self, arena))]
174 pub(super) fn pop(&mut self, arena: &mut NodeArena) -> ArenaCursorStackEntry {
175 let entry = self.stack.pop().expect("pop can't be called on empty stack");
176 self.needs_pop = false;
177 trace!(
178 target: TRACE_TARGET,
179 idx = ?entry.index,
180 path = ?self.entry_path(&entry),
181 "Popped stack entry",
182 );
183 let node = &arena[entry.index];
184
185 #[cfg(debug_assertions)]
186 if let ArenaSparseNode::Subtrie(s) = node {
187 let entry_path = self.path.slice_unchecked(0, entry.path_len as usize);
188 debug_assert_eq!(
189 s.path, entry_path,
190 "subtrie cached path {:?} does not match stack entry path {:?}",
191 s.path, entry_path,
192 );
193 }
194
195 if let Some(parent) = self.stack.last() {
196 let child_is_dirty = matches!(node.state_ref(), Some(ArenaSparseNodeState::Dirty));
197 if child_is_dirty {
198 let parent_branch_idx =
199 branch_idx(arena, parent.index).expect("parent must be a branch or extension");
200 *arena[parent.index].state_mut() = ArenaSparseNodeState::Dirty;
201 if parent_branch_idx != parent.index {
202 *arena[parent_branch_idx].state_mut() = ArenaSparseNodeState::Dirty;
203 }
204 }
205 }
206
207 entry
208 }
209
210 #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
213 pub(super) fn drain(&mut self, arena: &mut NodeArena) {
214 trace!(target: TRACE_TARGET, "Draining stack");
215 self.needs_pop = false;
216 while self.stack.len() > 1 {
217 self.pop(arena);
218 }
219 }
220
221 pub(super) fn head_logical_branch_path(&self, arena: &NodeArena) -> Nibbles {
224 self.logical_branch_path(arena, self.head_entry())
225 }
226
227 pub(super) fn head_logical_branch_path_len(&self, arena: &NodeArena) -> usize {
230 let head = self.head_entry();
231 head.path_len as usize + arena[head.index].extension_key().map_or(0, Nibbles::len)
232 }
233
234 pub(super) fn parent_logical_branch_path(&self, arena: &NodeArena) -> Nibbles {
237 self.logical_branch_path(arena, self.parent().expect("cursor must have a parent"))
238 }
239
240 pub(super) fn replace_head_index(
244 &mut self,
245 arena: &mut NodeArena,
246 root: &mut Index,
247 new_idx: Index,
248 ) {
249 let child_nibble = self.head_last_nibble();
250 let head = self.stack.last_mut().expect("cursor must have head");
251 let old_idx = head.index;
252 head.index = new_idx;
253
254 let Some(parent) = self.parent() else {
255 *root = new_idx;
256 return;
257 };
258
259 let child_nibble =
260 child_nibble.expect("if cursor has a parent then the head path can't be empty");
261
262 let parent_branch_idx =
263 branch_idx(arena, parent.index).expect("parent must be a branch or extension");
264 let parent_branch = arena[parent_branch_idx].branch_mut();
265 let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
266 .expect("child nibble not found in parent state_mask");
267
268 debug_assert_eq!(
269 parent_branch.children[child_idx].revealed_index(),
270 Some(old_idx),
271 "parent child at nibble {child_nibble} does not match old_idx",
272 );
273
274 parent_branch.children[child_idx] = BranchChild::revealed(new_idx);
275 }
276
277 #[instrument(level = "trace", target = TRACE_TARGET, skip_all, ret)]
291 pub(super) fn next(
292 &mut self,
293 arena: &mut NodeArena,
294 should_descend: impl Fn(usize, &ArenaSparseNode) -> bool,
295 ) -> NextResult {
296 if self.needs_pop {
297 self.pop(arena);
298 }
299
300 loop {
301 let Some(head) = self.stack.last_mut() else {
302 return NextResult::Done;
303 };
304 let head_idx = head.index;
305 let head_path_len = head.path_len as usize;
306
307 let Some(branch_idx) = branch_idx(arena, head_idx) else {
308 self.needs_pop = true;
309 return NextResult::NonBranch;
310 };
311 let branch = arena[branch_idx].branch_ref();
312
313 let state_mask = branch.state_mask;
314 let short_key = arena[head_idx].extension_key().copied().unwrap_or_default();
315 let start = head.next_dense_idx as usize;
316 let child_depth = self.stack.len();
317
318 let mut descended = false;
319 for (branch_child_idx, nibble) in BranchChildIter::new(state_mask) {
320 if branch_child_idx.get() < start {
321 continue;
322 }
323
324 let Some(child_idx) =
325 arena[branch_idx].branch_ref().children[branch_child_idx].revealed_index()
326 else {
327 continue;
328 };
329
330 if should_descend(child_depth, &arena[child_idx]) {
331 self.stack.last_mut().expect("head exists").next_dense_idx =
333 branch_child_idx.get() as u8 + 1;
334 self.path.truncate(head_path_len);
335 self.path.extend(&short_key);
336 self.path.push_unchecked(nibble);
337 self.push(arena, child_idx, self.path.len());
338 descended = true;
339 break;
340 }
341 }
342
343 if !descended {
344 self.needs_pop = true;
345 return NextResult::Branch;
346 }
347 }
348 }
349
350 #[instrument(level = "trace", target = TRACE_TARGET, skip(self, arena), ret)]
356 pub(super) fn seek(&mut self, arena: &mut NodeArena, full_path: &Nibbles) -> SeekResult {
357 let common = self.path.common_prefix_length(full_path);
361 while self.stack.len() > 1 && self.head_entry().path_len as usize > common {
362 self.pop(arena);
363 }
364
365 if self.head_entry().path_len as usize > common {
366 debug_assert!(
370 false,
371 "seek target {full_path:?} is not below the walk's root {:?}",
372 self.head_path(),
373 );
374 return SeekResult::Diverged;
375 }
376 self.path = *full_path;
377
378 loop {
379 let head = self.head_entry();
380 let head_idx = head.index;
381 let head_path_len = head.path_len as usize;
382
383 let short_key = arena[head_idx].extension_key().copied().unwrap_or_default();
384 let logical_len = head_path_len + short_key.len();
385
386 if full_path.len() < logical_len ||
389 (!short_key.is_empty() &&
390 full_path.slice_unchecked(head_path_len, logical_len) != short_key)
391 {
392 return SeekResult::Diverged;
393 }
394
395 let head_branch = match &arena[head_idx] {
396 ArenaSparseNode::EmptyRoot { .. } => {
397 return SeekResult::EmptyRoot;
398 }
399 ArenaSparseNode::Leaf { key, .. } => {
400 return if full_path.slice_unchecked(head_path_len, full_path.len()) == *key {
401 SeekResult::RevealedLeaf
402 } else {
403 SeekResult::Diverged
404 };
405 }
406 ArenaSparseNode::Branch(b) => b,
407 ArenaSparseNode::Extension { child, .. } => match child {
408 ExtensionChild::Revealed(index) => arena[*index].branch_ref(),
409 ExtensionChild::Blinded(_) => return SeekResult::Blinded,
410 },
411 ArenaSparseNode::Subtrie(_) => {
412 return SeekResult::RevealedSubtrie;
413 }
414 _ => unreachable!("unexpected node type on stack: {:?}", arena[head_idx]),
415 };
416
417 if full_path.len() == logical_len {
418 return SeekResult::Diverged;
419 }
420
421 let child_nibble = full_path.get_unchecked(logical_len);
422 let Some(branch_child_idx) = BranchChildIdx::new(head_branch.state_mask, child_nibble)
423 else {
424 return SeekResult::NoChild { child_nibble };
425 };
426
427 let Some(child_idx) = head_branch.children[branch_child_idx].revealed_index() else {
428 return SeekResult::Blinded;
429 };
430 self.push(arena, child_idx, logical_len + 1);
431 }
432 }
433
434 fn head_entry(&self) -> &ArenaCursorStackEntry {
436 self.stack.last().expect("cursor is non-empty")
437 }
438
439 fn entry_path(&self, entry: &ArenaCursorStackEntry) -> Nibbles {
441 self.path.slice_unchecked(0, entry.path_len as usize)
442 }
443
444 fn logical_branch_path(&self, arena: &NodeArena, entry: &ArenaCursorStackEntry) -> Nibbles {
446 let mut path = self.entry_path(entry);
447 if let Some(key) = arena[entry.index].extension_key() {
448 path.extend(key);
449 }
450 path
451 }
452}