|
| 1 | +//! A lazy range cursor over a B+tree snapshot. |
| 2 | +//! |
| 3 | +//! CoW trees keep no leaf sibling pointers (they would have to be copied on |
| 4 | +//! every edit), so iteration walks a root-to-leaf path held on a stack. The |
| 5 | +//! cursor reads the tree at a fixed `root`, giving a stable view for its whole |
| 6 | +//! life regardless of concurrent writers installing new roots. |
| 7 | +
|
| 8 | +use common::IoBackend; |
| 9 | +use pager::{PageId, Pager, HEADER_SIZE}; |
| 10 | + |
| 11 | +use crate::node::Node; |
| 12 | +use crate::Result; |
| 13 | + |
| 14 | +/// Iteration direction. |
| 15 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 16 | +pub enum Direction { |
| 17 | + /// Ascending key order. |
| 18 | + Forward, |
| 19 | + /// Descending key order. |
| 20 | + Backward, |
| 21 | +} |
| 22 | + |
| 23 | +/// A key/value pair yielded by a [`Cursor`]. |
| 24 | +pub type Item = (Vec<u8>, Vec<u8>); |
| 25 | + |
| 26 | +/// One level of the descent path. |
| 27 | +struct Frame { |
| 28 | + node: Node, |
| 29 | + /// Internal: the child index this frame descends through. Leaf: the next |
| 30 | + /// entry index a forward step would yield (a backward step yields `idx-1`). |
| 31 | + idx: usize, |
| 32 | +} |
| 33 | + |
| 34 | +/// A lazy, bounded iterator over `[lo, hi)` of a tree. |
| 35 | +/// |
| 36 | +/// Advance it with [`next_entry`](Cursor::next_entry), which returns `Ok(None)` |
| 37 | +/// at the end. Both bounds are optional; `lo` is inclusive and `hi` is exclusive. |
| 38 | +pub struct Cursor<'p, B: IoBackend> { |
| 39 | + pager: &'p Pager<B>, |
| 40 | + dir: Direction, |
| 41 | + lo: Option<Vec<u8>>, |
| 42 | + hi: Option<Vec<u8>>, |
| 43 | + path: Vec<Frame>, |
| 44 | +} |
| 45 | + |
| 46 | +impl<'p, B: IoBackend> Cursor<'p, B> { |
| 47 | + pub(crate) fn open( |
| 48 | + pager: &'p Pager<B>, |
| 49 | + root: PageId, |
| 50 | + dir: Direction, |
| 51 | + lo: Option<&[u8]>, |
| 52 | + hi: Option<&[u8]>, |
| 53 | + ) -> Result<Cursor<'p, B>> { |
| 54 | + let mut cursor = Cursor { |
| 55 | + pager, |
| 56 | + dir, |
| 57 | + lo: lo.map(<[u8]>::to_vec), |
| 58 | + hi: hi.map(<[u8]>::to_vec), |
| 59 | + path: Vec::new(), |
| 60 | + }; |
| 61 | + // Both directions seek to "the first entry ≥ the start bound": for |
| 62 | + // forward that bound is `lo` (and we step forward from it); for backward |
| 63 | + // it is `hi` (and we step backward into the range from it). An absent |
| 64 | + // bound is −∞ for forward (the start) but +∞ for backward (the end). |
| 65 | + let bound = match dir { |
| 66 | + Direction::Forward => cursor.lo.clone(), |
| 67 | + Direction::Backward => cursor.hi.clone(), |
| 68 | + }; |
| 69 | + match (dir, bound) { |
| 70 | + (Direction::Backward, None) => cursor.descend_rightmost(root)?, |
| 71 | + (_, b) => cursor.descend_lower_bound(root, b.as_deref())?, |
| 72 | + } |
| 73 | + Ok(cursor) |
| 74 | + } |
| 75 | + |
| 76 | + /// Yield the next pair, or `Ok(None)` when the range is exhausted. Fallible |
| 77 | + /// (a page read may fail), so this is not an [`Iterator`]. |
| 78 | + pub fn next_entry(&mut self) -> Result<Option<Item>> { |
| 79 | + match self.dir { |
| 80 | + Direction::Forward => self.next_forward(), |
| 81 | + Direction::Backward => self.next_backward(), |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + /// Collect the remaining pairs into a vector (convenience for callers/tests). |
| 86 | + pub fn collect_all(mut self) -> Result<Vec<Item>> { |
| 87 | + let mut out = Vec::new(); |
| 88 | + while let Some(item) = self.next_entry()? { |
| 89 | + out.push(item); |
| 90 | + } |
| 91 | + Ok(out) |
| 92 | + } |
| 93 | + |
| 94 | + fn read(&self, id: PageId) -> Result<Node> { |
| 95 | + let frame = self.pager.read_page(id)?; |
| 96 | + Node::decode(&frame[HEADER_SIZE..], id) |
| 97 | + } |
| 98 | + |
| 99 | + /// Build a path positioned at the first entry whose key is ≥ `bound` |
| 100 | + /// (or the leaf's end if none here — a caller step then crosses leaves). |
| 101 | + fn descend_lower_bound(&mut self, root: PageId, bound: Option<&[u8]>) -> Result<()> { |
| 102 | + let mut id = root; |
| 103 | + loop { |
| 104 | + let node = self.read(id)?; |
| 105 | + match &node { |
| 106 | + Node::Internal { keys, children } => { |
| 107 | + let ci = bound.map_or(0, |b| keys.partition_point(|k| k.as_slice() <= b)); |
| 108 | + let next = children[ci]; |
| 109 | + self.path.push(Frame { node, idx: ci }); |
| 110 | + id = next; |
| 111 | + } |
| 112 | + Node::Leaf { keys, .. } => { |
| 113 | + let start = bound.map_or(0, |b| keys.partition_point(|k| k.as_slice() < b)); |
| 114 | + self.path.push(Frame { node, idx: start }); |
| 115 | + return Ok(()); |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + /// Descend to the leftmost leaf of `id`, positioned at its first entry. |
| 122 | + fn descend_leftmost(&mut self, id: PageId) -> Result<()> { |
| 123 | + let mut id = id; |
| 124 | + loop { |
| 125 | + let node = self.read(id)?; |
| 126 | + match &node { |
| 127 | + Node::Internal { children, .. } => { |
| 128 | + let next = children[0]; |
| 129 | + self.path.push(Frame { node, idx: 0 }); |
| 130 | + id = next; |
| 131 | + } |
| 132 | + Node::Leaf { .. } => { |
| 133 | + self.path.push(Frame { node, idx: 0 }); |
| 134 | + return Ok(()); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + /// Descend to the rightmost leaf of `id`, positioned just past its last |
| 141 | + /// entry (so a backward step yields that last entry). |
| 142 | + fn descend_rightmost(&mut self, id: PageId) -> Result<()> { |
| 143 | + let mut id = id; |
| 144 | + loop { |
| 145 | + let node = self.read(id)?; |
| 146 | + match &node { |
| 147 | + Node::Internal { children, .. } => { |
| 148 | + let last = children.len() - 1; |
| 149 | + let next = children[last]; |
| 150 | + self.path.push(Frame { node, idx: last }); |
| 151 | + id = next; |
| 152 | + } |
| 153 | + Node::Leaf { keys, .. } => { |
| 154 | + let end = keys.len(); |
| 155 | + self.path.push(Frame { node, idx: end }); |
| 156 | + return Ok(()); |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + fn next_forward(&mut self) -> Result<Option<Item>> { |
| 163 | + loop { |
| 164 | + let Some(frame) = self.path.last() else { |
| 165 | + return Ok(None); |
| 166 | + }; |
| 167 | + if let Node::Leaf { keys, vals } = &frame.node { |
| 168 | + let idx = frame.idx; |
| 169 | + if idx < keys.len() { |
| 170 | + if self |
| 171 | + .hi |
| 172 | + .as_deref() |
| 173 | + .is_some_and(|hi| keys[idx].as_slice() >= hi) |
| 174 | + { |
| 175 | + self.path.clear(); |
| 176 | + return Ok(None); |
| 177 | + } |
| 178 | + let item = (keys[idx].clone(), vals[idx].clone()); |
| 179 | + if let Some(top) = self.path.last_mut() { |
| 180 | + top.idx += 1; |
| 181 | + } |
| 182 | + return Ok(Some(item)); |
| 183 | + } |
| 184 | + } |
| 185 | + // Leaf exhausted: drop it and advance the parent to the next child. |
| 186 | + self.path.pop(); |
| 187 | + if !self.advance_to_next_subtree()? { |
| 188 | + return Ok(None); |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + fn next_backward(&mut self) -> Result<Option<Item>> { |
| 194 | + loop { |
| 195 | + let Some(frame) = self.path.last() else { |
| 196 | + return Ok(None); |
| 197 | + }; |
| 198 | + if let Node::Leaf { keys, vals } = &frame.node { |
| 199 | + if frame.idx > 0 { |
| 200 | + let idx = frame.idx - 1; |
| 201 | + if self |
| 202 | + .lo |
| 203 | + .as_deref() |
| 204 | + .is_some_and(|lo| keys[idx].as_slice() < lo) |
| 205 | + { |
| 206 | + self.path.clear(); |
| 207 | + return Ok(None); |
| 208 | + } |
| 209 | + let item = (keys[idx].clone(), vals[idx].clone()); |
| 210 | + if let Some(top) = self.path.last_mut() { |
| 211 | + top.idx -= 1; |
| 212 | + } |
| 213 | + return Ok(Some(item)); |
| 214 | + } |
| 215 | + } |
| 216 | + // Start of this leaf: drop it and retreat to the previous child. |
| 217 | + self.path.pop(); |
| 218 | + if !self.retreat_to_prev_subtree()? { |
| 219 | + return Ok(None); |
| 220 | + } |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + /// After popping an exhausted leaf, move the path to the leftmost leaf of the |
| 225 | + /// next sibling subtree. Returns `false` if there is none. |
| 226 | + fn advance_to_next_subtree(&mut self) -> Result<bool> { |
| 227 | + while let Some(frame) = self.path.last_mut() { |
| 228 | + if let Node::Internal { children, .. } = &frame.node { |
| 229 | + frame.idx += 1; |
| 230 | + if frame.idx < children.len() { |
| 231 | + let child = children[frame.idx]; |
| 232 | + self.descend_leftmost(child)?; |
| 233 | + return Ok(true); |
| 234 | + } |
| 235 | + } |
| 236 | + self.path.pop(); |
| 237 | + } |
| 238 | + Ok(false) |
| 239 | + } |
| 240 | + |
| 241 | + /// After popping a leaf at its start, move the path to the rightmost leaf of |
| 242 | + /// the previous sibling subtree. Returns `false` if there is none. |
| 243 | + fn retreat_to_prev_subtree(&mut self) -> Result<bool> { |
| 244 | + while let Some(frame) = self.path.last_mut() { |
| 245 | + if let Node::Internal { .. } = &frame.node { |
| 246 | + if frame.idx > 0 { |
| 247 | + frame.idx -= 1; |
| 248 | + let child = match &frame.node { |
| 249 | + Node::Internal { children, .. } => children[frame.idx], |
| 250 | + Node::Leaf { .. } => return Ok(false), |
| 251 | + }; |
| 252 | + self.descend_rightmost(child)?; |
| 253 | + return Ok(true); |
| 254 | + } |
| 255 | + } |
| 256 | + self.path.pop(); |
| 257 | + } |
| 258 | + Ok(false) |
| 259 | + } |
| 260 | +} |
0 commit comments