mutcursor
This crate provides types to safely store mutable references to parent nodes, for backtracking during traversal of tree & graph structures.
[MutCursor] is more efficient because it avoids dynamic allocation, while [MutCursorVec] provides for an arbitrarily deep stack.
Usage
use MutCursor;
let mut tree = new;
let mut node_stack = new;
// Traverse to the last node
while node_stack.advance
assert_eq!;
assert_eq!;
node_stack.backtrack;
assert_eq!;
assert_eq!;
/// A simple stand-in for a recursive graph structure
Alternative(s)
This crate basically does the same thing as generic-cursors. However, there are several reasons to choose this crate:
-
The fixed-size stack used by [MutCursor] has lower overhead than a [Vec], and can be used in a
no_std
environment where dynamic allocation may be unavailable. -
The [MutCursor::try_map_into_mut] API enables some paterns that would be otherwise impossible.
Safety Thesis
Each &mut
reference stored by a [MutCursor] mutably borrows the reference beneath it in the stack. The stack root takes a mutable (and therefore exclusive) borrow of the node itself. Therefore the stack's top is an exclusive borrow.
You can imagine unrolling tree traversal into something like the code below, but this isn't amenable to looping. In essence each level
variable is preserved, but inaccessible because the level above is mutably borrowing it. The [MutCursor] object contains all the level
variables but only provides access to the top
let level_1 = &mut root;