brie_tree/
cursor.rs

1//! Cursor types for tree traversal and manipulation.
2//!
3//! This module contains the implementation of the core B+ Tree algorithms.
4
5use core::ops::Bound;
6use core::ops::Deref;
7use core::ptr::NonNull;
8use core::{hint, mem};
9
10use allocator_api2::alloc::Allocator;
11use allocator_api2::alloc::Global;
12
13use crate::Iter;
14use crate::IterMut;
15use crate::{
16    BTree, BTreeInteger, BTreeKey,
17    int::{int_from_key, key_from_int},
18    node::{NodePool, NodePos, NodeRef},
19    stack::Height,
20};
21
22/// Common base for mutable and immutable cursors.
23pub(crate) struct RawCursor<K: BTreeKey, V, A: Allocator, Ref: Deref<Target = BTree<K, V, A>>> {
24    /// Array of node and position pairs for each level of the tree.
25    ///
26    /// Invariants:
27    /// - Only levels between 0 and `btree.height` are valid.
28    /// - Positions in internal nodes must match the node on the next level of
29    ///   the stack. This implies that positions in internal nodes must be
30    ///   in-bounds.
31    /// - Positions in leaf nodes must point to a valid entry *except* if the
32    ///   cursor has reached the end of the tree, in which case it must point to
33    ///   the first `Int::MAX` key in the node.
34    ///
35    /// These invariants may be temporarily violated during cursor operations.
36    stack: <K::Int as BTreeInteger>::Stack,
37
38    /// Reference to the underlying `BTree`.
39    ///
40    /// This is either a mutable or immutable reference depending on the type of
41    /// cursor.
42    btree: Ref,
43}
44
45impl<K: BTreeKey, V, A: Allocator, Ref: Deref<Target = BTree<K, V, A>>> Clone
46    for RawCursor<K, V, A, Ref>
47where
48    Ref: Clone,
49{
50    #[inline]
51    fn clone(&self) -> Self {
52        Self {
53            stack: self.stack.clone(),
54            btree: self.btree.clone(),
55        }
56    }
57}
58
59impl<K: BTreeKey, V, A: Allocator, Ref: Deref<Target = BTree<K, V, A>>> RawCursor<K, V, A, Ref> {
60    /// Initializes a cursor to point to the given key.
61    #[inline]
62    fn seek(&mut self, key: <K::Int as BTreeInteger>::Raw) {
63        // Go down the tree, at each internal node selecting the first sub-tree
64        // with key greater than or equal to the search key. This sub-tree will
65        // only contain keys less than or equal to its key.
66        let mut height = self.btree.height;
67        let mut node = self.btree.root;
68        while let Some(down) = height.down() {
69            let keys = unsafe { node.keys(&self.btree.internal) };
70            let pos = unsafe { K::Int::search(keys, key) };
71            self.stack[height] = (node, pos);
72            node = unsafe { node.value(pos, &self.btree.internal).assume_init_read() };
73            height = down;
74        }
75
76        // Select the first leaf element with key greater than or equal to the
77        // search key.
78        let keys = unsafe { node.keys(&self.btree.leaf) };
79        let pos = unsafe { K::Int::search(keys, key) };
80        self.stack[height] = (node, pos);
81    }
82
83    /// Helper function to check that cursor invariants are maintained.
84    #[inline]
85    fn check_invariants(&self) {
86        if !cfg!(debug_assertions) {
87            return;
88        }
89
90        // The element at each internal level should point to the node lower on
91        // the stack.
92        let mut height = Height::leaf();
93        while let Some(up) = height.up(self.btree.height) {
94            let (node, pos) = self.stack[up];
95            let child = self.stack[height].0;
96            debug_assert_eq!(
97                unsafe { node.value(pos, &self.btree.internal).assume_init_read() },
98                child
99            );
100            height = up;
101        }
102
103        // If the leaf node points to an `Int::MAX` key then so must all
104        // internal nodes.
105        let (node, pos) = self.stack[Height::leaf()];
106        if unsafe { node.key(pos, &self.btree.leaf) } == K::Int::MAX {
107            let mut height = Height::leaf();
108            while let Some(up) = height.up(self.btree.height) {
109                let (node, pos) = self.stack[up];
110                debug_assert_eq!(unsafe { node.key(pos, &self.btree.internal) }, K::Int::MAX);
111                height = up;
112            }
113        }
114
115        debug_assert_eq!(self.stack[self.btree.height].0, self.btree.root);
116    }
117
118    /// Returns `true` if the cursor points to the end of the tree.
119    #[inline]
120    fn is_end(&self) -> bool {
121        self.entry().is_none()
122    }
123
124    /// Returns the key and a reference to the key and value at the cursor
125    /// position, or `None` if the cursor is pointing to the end of the tree.
126    #[inline]
127    fn entry(&self) -> Option<(K, NonNull<V>)> {
128        let (node, pos) = self.stack[Height::leaf()];
129        let key = unsafe { node.key(pos, &self.btree.leaf) };
130        let key = key_from_int(key)?;
131        let value = unsafe { node.values_ptr(&self.btree.leaf).add(pos.index()) };
132        Some((key, value.cast()))
133    }
134
135    /// Advances the cursor to the next element in the tree.
136    ///
137    /// # Panics
138    ///
139    /// Panics if the cursor is pointing to the end of the tree.
140    #[inline]
141    fn next(&mut self) {
142        assert!(!self.is_end(), "called next() on cursor already at end");
143
144        // Increment the position in the leaf node.
145        let (node, pos) = self.stack[Height::leaf()];
146        debug_assert_ne!(unsafe { node.key(pos, &self.btree.leaf) }, K::Int::MAX);
147        let pos = unsafe { pos.next() };
148        self.stack[Height::leaf()].1 = pos;
149
150        // If we reached the end of the leaf then we need to go up the tree to
151        // find the next leaf node.
152        if unsafe { node.key(pos, &self.btree.leaf) } == K::Int::MAX {
153            self.next_leaf_node();
154        }
155
156        self.check_invariants();
157    }
158
159    /// Advances the cursor to the previous element in the tree.
160    ///
161    /// If the cursor is already at the first element of the tree then this
162    /// method returns `false` and the cursor position is not moved.
163    #[inline]
164    fn prev(&mut self) -> bool {
165        // If we are at the start of the leaf then we need to go up the tree to
166        // find the previous leaf node.
167        let (_node, pos) = self.stack[Height::leaf()];
168        if pos.index() == 0 {
169            return self.prev_leaf_node();
170        }
171
172        // Decrement the position in the leaf node.
173        let pos = unsafe { pos.prev() };
174        self.stack[Height::leaf()].1 = pos;
175
176        self.check_invariants();
177
178        true
179    }
180
181    /// Advances the cursor to the start of the next leaf node.
182    ///
183    /// Leaves the cursor unmodified if this is the last leaf node of the tree.
184    #[inline]
185    fn next_leaf_node(&mut self) {
186        let mut height = Height::leaf();
187        let mut node = loop {
188            // If we reached the top of the tree then it means we are on the
189            // last entry at all levels of the tree. We've reached the end of
190            // the tree and can leave the cursor pointing on an `Int::MAX` key
191            // to indicate that.
192            let Some(up) = height.up(self.btree.height) else {
193                return;
194            };
195
196            // The last element of an internal node has a key of `Int::MAX`. If
197            // we are not at the last element then we can advance to the next
198            // sub-tree and go down that one.
199            let (node, pos) = &mut self.stack[up];
200            if unsafe { node.key(*pos, &self.btree.internal) } != K::Int::MAX {
201                *pos = unsafe { pos.next() };
202                let node = unsafe { node.value(*pos, &self.btree.internal).assume_init_read() };
203                break node;
204            }
205
206            // If we reached the end of an internal node, go up to the next
207            // level to find a sub-tree to go down.
208            height = up;
209        };
210
211        // We found a sub-tree, now go down all the way to a leaf node. Since
212        // these nodes are guaranteeed to be at least half full we can safely
213        // read the first element.
214        while let Some(down) = height.down() {
215            self.stack[height] = (node, pos!(0));
216            node = unsafe { node.value(pos!(0), &self.btree.internal).assume_init_read() };
217            height = down;
218        }
219        self.stack[Height::leaf()] = (node, pos!(0));
220
221        // The tree invariants guarantee that leaf nodes are always at least
222        // half full, except if this is the root node. However this can't be the
223        // root node since there is more than one node.
224        unsafe {
225            hint::assert_unchecked(node.key(pos!(0), &self.btree.leaf) != K::Int::MAX);
226        }
227    }
228
229    /// Advances the cursor to the end of the previous leaf node.
230    ///
231    /// Returns `false` and leaves the cursor unmodified if this is the first
232    /// leaf node of the tree.
233    #[inline]
234    fn prev_leaf_node(&mut self) -> bool {
235        let mut height = Height::leaf();
236        let mut node = loop {
237            // If we reached the top of the tree then it means we are on the
238            // first entry at all levels of the tree. We've reached the start of
239            // the tree and can leave the cursor pointing to the start of a
240            // leaf node to indicate that.
241            let Some(up) = height.up(self.btree.height) else {
242                return false;
243            };
244
245            // If we are not at the first element then we can advance to the
246            // previous sub-tree and go down that one.
247            let (node, pos) = &mut self.stack[up];
248            if pos.index() != 0 {
249                *pos = unsafe { pos.prev() };
250                let node = unsafe { node.value(*pos, &self.btree.internal).assume_init_read() };
251                break node;
252            }
253
254            // If we reached the start of an internal node, go up to the next
255            // level to find a sub-tree to go down.
256            height = up;
257        };
258
259        // We found a sub-tree, now go down all the way to a leaf node. Since
260        // these nodes are guaranteeed to be at least half full we can safely
261        // read the first element.
262        // TODO: Only search high half of the node.
263        while let Some(down) = height.down() {
264            let pos = unsafe { K::Int::search(node.keys(&self.btree.internal), K::Int::MAX) };
265            self.stack[height] = (node, pos);
266            node = unsafe { node.value(pos, &self.btree.internal).assume_init_read() };
267            height = down;
268        }
269        let pos = unsafe { K::Int::search(node.keys(&self.btree.leaf), K::Int::MAX) };
270        self.stack[Height::leaf()] = (node, unsafe { pos.prev() });
271
272        // The tree invariants guarantee that leaf nodes are always at least
273        // half full, except if this is the root node. However this can't be the
274        // root node since there is more than one node.
275        unsafe {
276            hint::assert_unchecked(pos.index() != 0);
277        }
278
279        self.check_invariants();
280
281        true
282    }
283}
284
285impl<K: BTreeKey, V, A: Allocator> RawCursor<K, V, A, &'_ mut BTree<K, V, A>> {
286    /// Propagates the maximum key in a leaf node to parent nodes.
287    ///
288    /// # Safety
289    ///
290    /// `key` must be the largest non-`MAX` key in the current leaf node.
291    #[inline]
292    unsafe fn update_leaf_max_key(&mut self, key: <K::Int as BTreeInteger>::Raw) {
293        let mut height = Height::leaf();
294        // This continues recursively as long as the parent sub-tree is the last
295        // one in its node, or the root of the tree is reached.
296        while let Some(up) = height.up(self.btree.height) {
297            let (node, pos) = self.stack[up];
298            if unsafe { node.key(pos, &self.btree.internal) } != K::Int::MAX {
299                unsafe {
300                    node.set_key(key, pos, &mut self.btree.internal);
301                }
302                break;
303            }
304            height = up;
305        }
306    }
307
308    /// Common code for `insert_before` and `insert_after`.
309    ///
310    /// After insertion the leaf position will be unchanged.
311    #[inline]
312    fn insert<const AFTER: bool>(&mut self, key: K, value: V) {
313        let key = int_from_key(key);
314        let (node, pos) = self.stack[Height::leaf()];
315
316        let insert_pos = if AFTER {
317            assert!(
318                !self.is_end(),
319                "called insert_after() on cursor already at end"
320            );
321            unsafe { pos.next() }
322        } else {
323            pos
324        };
325        let prev_key = unsafe { node.key(insert_pos, &self.btree.leaf) };
326
327        // If we are inserting the last key in a node then we need to update
328        // the sub-tree max key in the parent.
329        if prev_key == K::Int::MAX {
330            if AFTER {
331                unsafe {
332                    self.update_leaf_max_key(key);
333                }
334            } else {
335                // Note that because of the cursor invariants we don't need to
336                // update the sub-tree keys in any parent nodes:
337                // - If the cursor is at the end of the tree then all keys on
338                //   the stack have value `Int::MAX` already.
339                // - Otherwise the insertion doesn't happen at the end of the
340                //   node, so the maximum key doesn't change.
341                debug_assert!(self.is_end());
342            }
343        }
344
345        // Check if this insertion will cause the leaf node to become completely
346        // full. Specifically that after insertion the last key will *not* be
347        // `Int::MAX`, which violates the node invariant.
348        let overflow = unsafe { node.key(pos!(K::Int::B - 2), &self.btree.leaf) } != K::Int::MAX;
349
350        // Save the next leaf pointer since it is overwritten by insertion.
351        let next_leaf = unsafe { node.next_leaf(&self.btree.leaf) };
352
353        // Insert the new key and value in the leaf. Use a fast path for
354        // inserting at the end of a node. This helps with common cases when
355        // appending to the end of a tree.
356        if prev_key == K::Int::MAX {
357            unsafe {
358                node.set_key(key, insert_pos, &mut self.btree.leaf);
359                node.value_mut(insert_pos, &mut self.btree.leaf)
360                    .write(value);
361            }
362        } else {
363            unsafe {
364                node.insert_key(key, insert_pos, K::Int::B, &mut self.btree.leaf);
365                node.insert_value(value, insert_pos, K::Int::B, &mut self.btree.leaf);
366            }
367        }
368
369        // If insertion didn't overflow then we are done.
370        if !overflow {
371            // Restore next_leaf which will have been overwritten by the insert.
372            unsafe {
373                node.set_next_leaf(next_leaf, &mut self.btree.leaf);
374            }
375            return;
376        }
377
378        // At this point the leaf node is completely full and needs to be split
379        // to maintain the node invariant.
380
381        // Record the last key of the first half of the node. This will become
382        // the key for the left sub-tree in the parent node.
383        let mut mid_key = unsafe { node.key(pos!(K::Int::B / 2 - 1), &self.btree.leaf) };
384
385        // Allocate a new node and move the second half of the current node to
386        // it.
387        let new_uninit_node = unsafe { self.btree.leaf.alloc_node(&self.btree.alloc) };
388        let mut new_node = unsafe { node.split_into(new_uninit_node, &mut self.btree.leaf) };
389
390        // Update the next-leaf pointers for both nodes.
391        unsafe {
392            new_node.set_next_leaf(next_leaf, &mut self.btree.leaf);
393            node.set_next_leaf(Some(new_node), &mut self.btree.leaf);
394        }
395
396        // Keep track of where the cursor is in the tree by adjusting the
397        // position on the stack if we were in the second half of the node that
398        // got split.
399        let mut in_right_split = if let Some(new_pos) = pos.split_right_half() {
400            self.stack[Height::leaf()] = (new_node, new_pos);
401            true
402        } else {
403            false
404        };
405
406        // Propagate the split by inserting the new node in the next level of
407        // the tree. This may cause that node to also be split if it gets full.
408        let mut height = Height::leaf();
409        while let Some(up) = height.up(self.btree.height) {
410            height = up;
411            let (node, mut pos) = self.stack[height];
412
413            // The last 2 keys of leaf nodes are always `Int::MAX` so we can
414            // check if an insertion will cause an overflow by looking at
415            // whether the key at `B - 3` is `Int::MAX`.
416            let overflow =
417                unsafe { node.key(pos!(K::Int::B - 3), &self.btree.internal) } != K::Int::MAX;
418
419            // The existing key for this sub-tree (max of all keys in sub-tree)
420            // is correct for the second node of the split. Similarly the
421            // existing value already points to the first node of the split. So
422            // insert the new key before the existing one and the new value
423            // after the existing one.
424            unsafe {
425                node.insert_key(mid_key, pos, K::Int::B, &mut self.btree.internal);
426                node.insert_value(new_node, pos.next(), K::Int::B, &mut self.btree.internal);
427            }
428
429            // If the node below us ended up on the right side of the split,
430            // adjust the cursor position to point to the newly inserted node.
431            if in_right_split {
432                pos = unsafe { pos.next() };
433            }
434            self.stack[height].1 = pos;
435
436            // If the node is not full then we're done.
437            if !overflow {
438                self.check_invariants();
439                return;
440            }
441
442            // Record the last key of the first half of the node. This will
443            // become the key for the left sub-tree in the parent node.
444            mid_key = unsafe { node.key(pos!(K::Int::B / 2 - 1), &self.btree.internal) };
445
446            // Set the last key of the first half to `Int::MAX` to indicate that
447            // it is the last element in this node.
448            unsafe {
449                node.set_key(
450                    K::Int::MAX,
451                    pos!(K::Int::B / 2 - 1),
452                    &mut self.btree.internal,
453                );
454            }
455
456            // Allocate a new node and move the second half of the current node
457            // to it.
458            let new_uninit_node = unsafe { self.btree.internal.alloc_node(&self.btree.alloc) };
459            new_node = unsafe { node.split_into(new_uninit_node, &mut self.btree.internal) };
460
461            // Keep track of where the cursor is in the tree by adjusting the
462            // position on the stack if we were in the second half of the node
463            // that got split.
464            in_right_split = if let Some(new_pos) = pos.split_right_half() {
465                self.stack[height] = (new_node, new_pos);
466                true
467            } else {
468                false
469            };
470        }
471
472        // If we reached the root of the tree then we need to add a new level to
473        // the tree and create a new root node.
474        let new_uninit_root = unsafe { self.btree.internal.alloc_node(&self.btree.alloc) };
475
476        // The new root only contains 2 elements: the original root node and the
477        // newly created split node. The only non-MAX key is the first one which
478        // holds the maximum key in the left sub-tree.
479        let new_root;
480        unsafe {
481            new_root = new_uninit_root.init_keys(&mut self.btree.internal);
482            new_root.set_key(mid_key, pos!(0), &mut self.btree.internal);
483            new_root
484                .value_mut(pos!(0), &mut self.btree.internal)
485                .write(self.btree.root);
486            new_root
487                .value_mut(pos!(1), &mut self.btree.internal)
488                .write(new_node);
489        }
490        self.btree.root = new_root;
491
492        // Increment the height of the tree. The `expect` should never fail here
493        // since we calculated the maximum possible height for the tree
494        // statically as `Height::max`.
495        self.btree.height = self
496            .btree
497            .height
498            .up(Height::max())
499            .expect("exceeded maximum height");
500
501        // Set up the new level in the cursor stack.
502        let pos = if in_right_split { pos!(1) } else { pos!(0) };
503        self.stack[self.btree.height] = (new_root, pos);
504
505        self.check_invariants();
506    }
507
508    /// Replaces the key and value of the element at the given position.
509    ///
510    /// # Panics
511    ///
512    /// Panics if the cursor is pointing to the end of the tree.
513    #[inline]
514    fn replace(&mut self, key: K, value: V) -> (K, V) {
515        let key = int_from_key(key);
516
517        let (node, pos) = self.stack[Height::leaf()];
518        let old_key = unsafe { node.key(pos, &self.btree.leaf) };
519        let old_key = key_from_int(old_key).expect("called replace() on cursor already at end");
520
521        // If we are replacing the last key in a node then we need to update the
522        // sub-tree max key in the parent.
523        unsafe {
524            if node.key(pos.next(), &self.btree.leaf) == K::Int::MAX {
525                self.update_leaf_max_key(key);
526            }
527        }
528
529        // Then actually replace the key and value in the leaf node.
530        unsafe {
531            node.set_key(key, pos, &mut self.btree.leaf);
532        }
533        let old_value = unsafe {
534            mem::replace(
535                node.value_mut(pos, &mut self.btree.leaf).assume_init_mut(),
536                value,
537            )
538        };
539
540        (old_key, old_value)
541    }
542
543    /// Removes the element to the right of the cursor and returns it.
544    ///
545    /// # Panics
546    ///
547    /// Panics if the cursor is pointing to the end of the tree.
548    #[inline]
549    fn remove(&mut self) -> (K, V) {
550        let (node, pos) = self.stack[Height::leaf()];
551
552        // Check if this deletion will cause the leaf node to become less than
553        // half full. Specifically that after deletion last key in the first
554        // half will be`Int::MAX`, which violates the node invariant.
555        let underflow = unsafe { node.key(pos!(K::Int::B / 2), &self.btree.leaf) } == K::Int::MAX;
556
557        // Extract the key and value that will be returned by this function.
558        let key = unsafe {
559            key_from_int(node.key(pos, &self.btree.leaf))
560                .expect("called remove() on cursor already at end")
561        };
562        let value = unsafe { node.value(pos, &self.btree.leaf).assume_init_read() };
563
564        // Remove the key and value from the node.
565        unsafe {
566            node.remove_key(pos, &mut self.btree.leaf);
567            node.remove_value(pos, &mut self.btree.leaf);
568        }
569
570        // If we removed the last key in a node then we need to update the
571        // sub-tree max key in the parent.
572        unsafe {
573            if node.key(pos, &self.btree.leaf) == K::Int::MAX && self.btree.height != Height::leaf()
574            {
575                // Leaf nodes must be at least half full if they are not the
576                // root node.
577                let new_max = node.key(pos.prev(), &self.btree.leaf);
578                self.update_leaf_max_key(new_max);
579            }
580        }
581
582        // If the leaf node is now less than half-full, we need to either steal
583        // an element from a sibling node or merge it with a sibling to restore
584        // the node invariant that it must always be at least half full..
585        if underflow {
586            // If there is only a single leaf node in the tree then it is
587            // allowed to have as little as zero elements and cannot underflow.
588            if let Some(up) = Height::leaf().up(self.btree.height) {
589                // `node` is less than half-full, try to restore the invariant
590                // by stealing from another node or merging it.
591                let up_node = unsafe {
592                    self.handle_underflow(Height::leaf(), up, node, true, |btree| &mut btree.leaf)
593                };
594                if let Some(mut node) = up_node {
595                    let mut height = up;
596                    loop {
597                        if let Some(up) = height.up(self.btree.height) {
598                            // Check if this node is less than half full. A
599                            // half-full internal node would have the first
600                            // `Int::MAX` key at `B / 2 - 1`.
601                            if unsafe { node.key(pos!(K::Int::B / 2 - 2), &self.btree.internal) }
602                                == K::Int::MAX
603                            {
604                                // `node` is less than half-full, try to restore
605                                // the invariant by stealing from another node
606                                // or merging it.
607                                if let Some(up_node) = unsafe {
608                                    self.handle_underflow(height, up, node, false, |btree| {
609                                        &mut btree.internal
610                                    })
611                                } {
612                                    // If the underflow was resolved by merging
613                                    // then the parent node could have become
614                                    // less than half-full itself. Loop back
615                                    // and do the same with the parent.
616                                    node = up_node;
617                                    height = up;
618                                    continue;
619                                }
620                            }
621                        } else {
622                            // We've reached the root node. If it only has a
623                            // single element then we can pop a level off the
624                            // tree and free the old root node.
625                            debug_assert_eq!(node, self.btree.root);
626                            if unsafe { node.key(pos!(0), &self.btree.internal) } == K::Int::MAX {
627                                unsafe {
628                                    self.btree.root = node
629                                        .value(pos!(0), &self.btree.internal)
630                                        .assume_init_read();
631                                }
632                                unsafe {
633                                    self.btree.internal.free_node(node);
634                                }
635                                self.btree.height = height.down().unwrap();
636                            }
637                        }
638                        break;
639                    }
640                }
641            }
642        }
643
644        // If we ended up at the end of a leaf node due to the deletion, advance
645        // the cursor to the next element.
646        if self.is_end() {
647            self.next_leaf_node();
648        }
649
650        self.check_invariants();
651
652        (key, value)
653    }
654
655    /// Given `child` which is less than half full, restores the invariant that
656    /// nodes must be at least half full by stealing an element from a sibling
657    /// or merging `child` with a sibling node.
658    ///
659    /// If this is resolved through merging, this function returns a `NodeRef`
660    /// to the parent of `child` which may now be under-filled.
661    ///
662    /// # Safety
663    ///
664    /// - `up` is the level above the one containing `child`.
665    /// - `child` must have exact `B / 2 - 1` elements.
666    /// - `child_is_leaf` indicates whether `child` is a leaf node and
667    ///   `child_pool` returns a reference to the appropriate `NodePool`.
668    #[inline]
669    unsafe fn handle_underflow<ChildValue>(
670        &mut self,
671        height: Height<K::Int>,
672        up: Height<K::Int>,
673        child: NodeRef,
674        child_is_leaf: bool,
675        child_pool: impl Fn(&mut BTree<K, V, A>) -> &mut NodePool<K::Int, ChildValue>,
676    ) -> Option<NodeRef> {
677        // The child must have exactly `B / 2 - 1` elements.
678        debug_assert_eq!(
679            unsafe {
680                if child_is_leaf {
681                    child.leaf_end(&self.btree.leaf).index()
682                } else {
683                    child.internal_end(&self.btree.internal).index()
684                }
685            },
686            K::Int::B / 2 - 1
687        );
688
689        // Check if the child is the last sub-tree in its parent. The last
690        // sub-tree always has a key of `Int::MAX`.
691        let (node, pos) = self.stack[up];
692        debug_assert_eq!(
693            unsafe { node.value(pos, &self.btree.internal).assume_init_read() },
694            child
695        );
696        let child_subtree_max = unsafe { node.key(pos, &self.btree.internal) };
697
698        // We now need to select a sibling node to steal from or merge with.
699        // Prefer using the next sub-tree as a sibling since it has a more
700        // efficient code path.
701        if child_subtree_max != K::Int::MAX {
702            let sibling = unsafe {
703                node.value(pos.next(), &self.btree.internal)
704                    .assume_init_read()
705            };
706
707            // We can steal from the sibling if it is more than half-full.
708            let can_steal = unsafe {
709                sibling.key(
710                    if child_is_leaf {
711                        pos!(K::Int::B / 2)
712                    } else {
713                        pos!(K::Int::B / 2 - 1)
714                    },
715                    child_pool(self.btree),
716                )
717            } != K::Int::MAX;
718
719            if can_steal {
720                unsafe {
721                    // Remove the first key/value from the sibling.
722                    let key = sibling.key(pos!(0), child_pool(self.btree));
723                    let value = sibling
724                        .value(pos!(0), child_pool(self.btree))
725                        .assume_init_read();
726                    sibling.remove_key(pos!(0), child_pool(self.btree));
727                    sibling.remove_value(pos!(0), child_pool(self.btree));
728
729                    if child_is_leaf {
730                        // If the child is a leaf node then we can just insert
731                        // the key/value at `B / 2 - 1` since we know the child
732                        // currently has exactly that many elements.
733                        child.set_key(key, pos!(K::Int::B / 2 - 1), child_pool(self.btree));
734                        child
735                            .value_mut(pos!(K::Int::B / 2 - 1), child_pool(self.btree))
736                            .write(value);
737                    } else {
738                        // If the child is an internal node then we need to set
739                        // the key for the *previous* sub-tree (which is
740                        // currently `Int::MAX`) to `child_subtree_max` which is
741                        // the maximum key for that sub-tree before the steal.
742                        child.set_key(
743                            child_subtree_max,
744                            pos!(K::Int::B / 2 - 2),
745                            child_pool(self.btree),
746                        );
747                        child
748                            .value_mut(pos!(K::Int::B / 2 - 1), child_pool(self.btree))
749                            .write(value);
750                    }
751
752                    // The steal has caused the largest key in `child` to
753                    // increase (since we appended to its end). Update the key
754                    // for this sub-tree in the parent to the key for the stolen
755                    // element.
756                    node.set_key(key, pos, &mut self.btree.internal);
757                }
758
759                // Stealing can't cause recursive underflows.
760                None
761            } else {
762                unsafe {
763                    // The sibling has exactly `B / 2` elements, move those to
764                    // the end of the child which has exactly `B / 2 - 1`
765                    // elements. This results in a full node with the maximum of
766                    // `B - 1` elements.
767                    child.merge_from(
768                        sibling,
769                        pos!(K::Int::B / 2 - 1),
770                        K::Int::B / 2,
771                        child_pool(self.btree),
772                    );
773
774                    // If this is an internal node then we need to copy the
775                    // previous maximum key for the child's sub-tree to slot
776                    // `B / 2 - 2`  which previously contained MAX.
777                    if !child_is_leaf {
778                        child.set_key(
779                            child_subtree_max,
780                            pos!(K::Int::B / 2 - 2),
781                            child_pool(self.btree),
782                        );
783                    }
784
785                    // Update the next leaf pointer if this is a leaf node.
786                    if child_is_leaf {
787                        let next_leaf = sibling.next_leaf(child_pool(self.btree));
788                        child.set_next_leaf(next_leaf, child_pool(self.btree));
789                    }
790
791                    // The sibling is no longer in the tree, free its node.
792                    child_pool(self.btree).free_node(sibling);
793
794                    // Remove the sibling node from its parent. We keep the key
795                    // of `sibling` and remove that of `child` because the key
796                    // should hold the maximum key in the sub-tree.
797                    node.remove_key(pos, &mut self.btree.internal);
798                    node.remove_value(pos.next(), &mut self.btree.internal);
799                }
800
801                // Merging may cause the parent node to become under-sized.
802                Some(node)
803            }
804        } else {
805            let sibling = unsafe {
806                node.value(pos.prev(), &self.btree.internal)
807                    .assume_init_read()
808            };
809
810            // We can steal from the sibling if it is more than half-full.
811            let can_steal = unsafe {
812                sibling.key(
813                    if child_is_leaf {
814                        pos!(K::Int::B / 2)
815                    } else {
816                        pos!(K::Int::B / 2 - 1)
817                    },
818                    child_pool(self.btree),
819                )
820            } != K::Int::MAX;
821
822            if can_steal {
823                unsafe {
824                    // Find the position of the last element in the sibling.
825                    let sibling_end = if child_is_leaf {
826                        sibling.leaf_end(child_pool(self.btree))
827                    } else {
828                        sibling.internal_end(child_pool(self.btree))
829                    };
830                    let sibling_last = sibling_end.prev();
831
832                    if child_is_leaf {
833                        // If the child is a leaf node then we can just take the
834                        // last key/value of the sibling and insert it at the
835                        // start of the child.
836                        //
837                        // We use a node size of `B / 2 + 1` so that the
838                        // operation becomes a copy of exactly `B / 2` elements.
839                        // All elements in the second half of the node are
840                        // absent anyways. This also preserves the next leaf
841                        // pointer.
842                        let key = sibling.key(sibling_last, child_pool(self.btree));
843                        let value = sibling
844                            .value(sibling_last, child_pool(self.btree))
845                            .assume_init_read();
846                        child.insert_key(key, pos!(0), K::Int::B / 2 + 1, child_pool(self.btree));
847                        child.insert_value(
848                            value,
849                            pos!(0),
850                            K::Int::B / 2 + 1,
851                            child_pool(self.btree),
852                        );
853
854                        // Stealing the last element of `sibling` has caused
855                        // its largest key to decrease. Update the key for this
856                        // sub-tree in the parent to the key for the new last
857                        // element.
858                        let sibling_max_key =
859                            sibling.key(sibling_last.prev(), child_pool(self.btree));
860                        node.set_key(sibling_max_key, pos.prev(), &mut self.btree.internal);
861
862                        // Now actually shrink the sibling by removing its last
863                        // element.
864                        sibling.set_key(K::Int::MAX, sibling_last, child_pool(self.btree));
865                    } else {
866                        // If the child is a internal node then we need to
867                        // recover the maximum key in the sibling from `node`
868                        // and insert that along with the last sub-tree in the
869                        // sibling into the child.
870                        //
871                        // We use a node size of `B / 2 + 1` so that the
872                        // operation becomes a copy of exactly `B / 2` elements.
873                        // All elements in the second half of the node are
874                        // absent anyways. This also preserves the next leaf
875                        // pointer.
876                        let sibling_max_key = node.key(pos.prev(), &self.btree.internal);
877                        let value = sibling
878                            .value(sibling_last, child_pool(self.btree))
879                            .assume_init_read();
880                        child.insert_key(
881                            sibling_max_key,
882                            pos!(0),
883                            K::Int::B / 2 + 1,
884                            child_pool(self.btree),
885                        );
886                        child.insert_value(
887                            value,
888                            pos!(0),
889                            K::Int::B / 2 + 1,
890                            child_pool(self.btree),
891                        );
892
893                        // Stealing the last element of `sibling` has caused
894                        // its largest key to decrease. Update the key for this
895                        // sub-tree in the parent to the key for the new last
896                        // element.
897                        let sibling_max_key =
898                            sibling.key(sibling_last.prev(), child_pool(self.btree));
899                        node.set_key(sibling_max_key, pos.prev(), &mut self.btree.internal);
900
901                        // Now actually shrink the sibling by removing its last
902                        // element.
903                        sibling.set_key(K::Int::MAX, sibling_last.prev(), child_pool(self.btree));
904                    }
905
906                    // After stealing, we need to adjust the cursor position for
907                    // the child.
908                    self.stack[height].1 = self.stack[height].1.next();
909                }
910
911                // Stealing can't cause recursive underflows.
912                None
913            } else {
914                unsafe {
915                    // The child has exactly `B / 2 - 1` elements, move those to
916                    // the end of the sibling which has exactly `B / 2`
917                    // elements. This results in a full node with the maximum of
918                    // `B - 1` elements.
919                    sibling.merge_from(
920                        child,
921                        pos!(K::Int::B / 2),
922                        K::Int::B / 2 - 1,
923                        child_pool(self.btree),
924                    );
925
926                    // If this is an internal node then we need to copy the
927                    // previous maximum key for the sibling's sub-tree to slot
928                    // `B / 2 - 1`  which previously contained MAX.
929                    if !child_is_leaf {
930                        let sibling_max_key = node.key(pos.prev(), &self.btree.internal);
931                        sibling.set_key(
932                            sibling_max_key,
933                            pos!(K::Int::B / 2 - 1),
934                            child_pool(self.btree),
935                        );
936                    }
937
938                    // Update the next leaf pointer if this is a leaf node.
939                    if child_is_leaf {
940                        let next_leaf = child.next_leaf(child_pool(self.btree));
941                        sibling.set_next_leaf(next_leaf, child_pool(self.btree));
942                    }
943
944                    // The child is no longer in the tree, free its node.
945                    child_pool(self.btree).free_node(child);
946
947                    // Remove the child node from its parent. We keep the key
948                    // of `child` and remove that of `sibling` because the key
949                    // should hold the maximum key in the sub-tree.
950                    node.remove_key(pos.prev(), &mut self.btree.internal);
951                    node.remove_value(pos, &mut self.btree.internal);
952
953                    // After merging, we need to adjust the cursor position for
954                    // the child and parent.
955                    self.stack[up].1 = self.stack[up].1.prev();
956                    self.stack[height] = (
957                        sibling,
958                        NodePos::new_unchecked(self.stack[height].1.index() + K::Int::B / 2),
959                    );
960                }
961
962                // Merging may cause the parent node to become under-sized.
963                Some(node)
964            }
965        }
966    }
967}
968
969/// A cursor over the elements of a [`BTree`].
970///
971/// Cursors point either to an element in the tree or to the end of the tree.
972///
973/// Iterators are more efficient than cursors. Prefer using them if you don't
974/// need reverse iteration or if you don't need to insert or remove elements in
975/// the tree.
976///
977/// This type is returned by [`BTree::cursor_at`] and [`BTree::cursor`].
978pub struct Cursor<'a, K: BTreeKey, V, A: Allocator = Global> {
979    raw: RawCursor<K, V, A, &'a BTree<K, V, A>>,
980}
981
982impl<K: BTreeKey, V, A: Allocator> Clone for Cursor<'_, K, V, A> {
983    #[inline]
984    fn clone(&self) -> Self {
985        Self {
986            raw: self.raw.clone(),
987        }
988    }
989}
990
991impl<'a, K: BTreeKey, V, A: Allocator> Cursor<'a, K, V, A> {
992    /// Returns `true` if the cursor points to the end of the tree.
993    #[inline]
994    pub fn is_end(&self) -> bool {
995        self.raw.is_end()
996    }
997
998    /// Returns the key of the element that the cursor is currently pointing to,
999    /// or `None` if the cursor is pointing to the end of the tree.
1000    #[inline]
1001    pub fn key(&self) -> Option<K> {
1002        self.entry().map(|(k, _v)| k)
1003    }
1004
1005    /// Returns a reference to the value that the cursor is currently
1006    /// pointing to, or `None` if the cursor is pointing to the end of the tree.
1007    #[inline]
1008    pub fn value(&self) -> Option<&'a V> {
1009        self.entry().map(|(_k, v)| v)
1010    }
1011
1012    /// Returns the key and a reference to the value that the cursor is
1013    /// currently pointing to, or `None` if the cursor is pointing to the end of
1014    /// the tree.
1015    #[inline]
1016    pub fn entry(&self) -> Option<(K, &'a V)> {
1017        self.raw.entry().map(|(k, v)| (k, unsafe { v.as_ref() }))
1018    }
1019
1020    /// Advances the cursor to the next element in the tree.
1021    ///
1022    /// # Panics
1023    ///
1024    /// Panics if the cursor is pointing to the end of the tree.
1025    #[inline]
1026    pub fn next(&mut self) {
1027        self.raw.next();
1028    }
1029
1030    /// Advances the cursor to the previous element in the tree.
1031    ///
1032    /// If the cursor is already at the first element of the tree then this
1033    /// method returns `false` and the cursor position is not moved.
1034    #[inline]
1035    pub fn prev(&mut self) -> bool {
1036        self.raw.prev()
1037    }
1038
1039    /// Returns an iterator starting a the current element.
1040    ///
1041    /// Iterators are more efficient than cursors. Prefer using them if you don't
1042    /// need reverse iteration or if you don't need to insert or remove elements in
1043    /// the tree.
1044    #[inline]
1045    pub fn iter(&self) -> Iter<'a, K, V, A> {
1046        let (node, pos) = self.raw.stack[Height::leaf()];
1047        Iter {
1048            raw: crate::RawIter { node, pos },
1049            btree: self.raw.btree,
1050        }
1051    }
1052}
1053
1054/// A mutable cursor over the elements of a [`BTree`] which allows editing
1055/// operations.
1056///
1057/// Cursors point either to an element in the tree or to the end of the tree.
1058///
1059/// Iterators are more efficient than cursors. Prefer using them if you don't
1060/// need reverse iteration or if you don't need to insert or remove elements in
1061/// the tree.
1062///
1063/// This type is returned by [`BTree::cursor_mut_at`] and [`BTree::cursor_mut`].
1064pub struct CursorMut<'a, K: BTreeKey, V, A: Allocator = Global> {
1065    raw: RawCursor<K, V, A, &'a mut BTree<K, V, A>>,
1066}
1067
1068impl<'a, K: BTreeKey, V, A: Allocator> CursorMut<'a, K, V, A> {
1069    /// Internal constructor for an uninitialized cursor.
1070    ///
1071    /// This allows cursors to be initialized in-place, which works around
1072    /// rustc's poor support for move-elimination.
1073    ///
1074    /// # Safety
1075    ///
1076    /// The cursor must be initialized before use by calling `seek`.
1077    #[inline]
1078    pub(crate) unsafe fn uninit(btree: &'a mut BTree<K, V, A>) -> Self {
1079        Self {
1080            raw: RawCursor {
1081                stack: <K::Int as BTreeInteger>::Stack::default(),
1082                btree,
1083            },
1084        }
1085    }
1086
1087    /// Initializes a cursor to point to the given key.
1088    #[inline]
1089    pub(crate) fn seek(&mut self, key: <K::Int as BTreeInteger>::Raw) {
1090        self.raw.seek(key);
1091    }
1092
1093    /// Returns `true` if the cursor points to the end of the tree.
1094    #[inline]
1095    pub fn is_end(&self) -> bool {
1096        self.entry().is_none()
1097    }
1098
1099    /// Returns the key of the element that the cursor is currently pointing to,
1100    /// or `None` if the cursor is pointing to the end of the tree.
1101    #[inline]
1102    pub fn key(&self) -> Option<K> {
1103        self.entry().map(|(k, _v)| k)
1104    }
1105
1106    /// Returns a reference to the value that the cursor is currently
1107    /// pointing to, or `None` if the cursor is pointing to the end of the tree.
1108    #[inline]
1109    pub fn value(&self) -> Option<&V> {
1110        self.entry().map(|(_k, v)| v)
1111    }
1112
1113    /// Returns a mutable reference to the value that the cursor is currently
1114    /// pointing to, or `None` if the cursor is pointing to the end of the tree.
1115    #[inline]
1116    pub fn value_mut(&mut self) -> Option<&mut V> {
1117        self.entry_mut().map(|(_k, v)| v)
1118    }
1119
1120    /// Returns the key and a reference to the value that the cursor is
1121    /// currently pointing to, or `None` if the cursor is pointing to the end of
1122    /// the tree.
1123    #[inline]
1124    pub fn entry(&self) -> Option<(K, &V)> {
1125        self.raw.entry().map(|(k, v)| (k, unsafe { v.as_ref() }))
1126    }
1127
1128    /// Returns the key and a mutable reference to the value that the cursor is
1129    /// currently pointing to, or `None` if the cursor is pointing to the end of
1130    /// the tree.
1131    #[inline]
1132    pub fn entry_mut(&mut self) -> Option<(K, &mut V)> {
1133        self.raw
1134            .entry()
1135            .map(|(k, mut v)| (k, unsafe { v.as_mut() }))
1136    }
1137
1138    /// Advances the cursor to the next element in the tree.
1139    ///
1140    /// # Panics
1141    ///
1142    /// Panics if the cursor is pointing to the end of the tree.
1143    #[inline]
1144    pub fn next(&mut self) {
1145        self.raw.next();
1146    }
1147
1148    /// Advances the cursor to the previous element in the tree.
1149    ///
1150    /// If the cursor is already at the first element of the tree then this
1151    /// method returns `false` and the cursor position is not moved.
1152    #[inline]
1153    pub fn prev(&mut self) -> bool {
1154        self.raw.prev()
1155    }
1156
1157    /// Returns an iterator starting a the current element.
1158    ///
1159    /// Iterators are more efficient than cursors. Prefer using them if you don't
1160    /// need reverse iteration or if you don't need to insert or remove elements in
1161    /// the tree.
1162    #[inline]
1163    pub fn iter(&self) -> Iter<'_, K, V, A> {
1164        let (node, pos) = self.raw.stack[Height::leaf()];
1165        Iter {
1166            raw: crate::RawIter { node, pos },
1167            btree: self.raw.btree,
1168        }
1169    }
1170
1171    /// Returns a mutable iterator starting a the current element.
1172    ///
1173    /// Iterators are more efficient than cursors. Prefer using them if you don't
1174    /// need reverse iteration or if you don't need to insert or remove elements in
1175    /// the tree.
1176    #[inline]
1177    pub fn iter_mut(&mut self) -> IterMut<'_, K, V, A> {
1178        let (node, pos) = self.raw.stack[Height::leaf()];
1179        IterMut {
1180            raw: crate::RawIter { node, pos },
1181            btree: self.raw.btree,
1182        }
1183    }
1184
1185    /// Returns an iterator starting a the current element.
1186    ///
1187    /// Unlike [`CursorMut::iter`] the returned iterator has the same lifetime
1188    /// as the cursor and consumes the cursor.
1189    ///
1190    /// Iterators are more efficient than cursors. Prefer using them if you don't
1191    /// need reverse iteration or if you don't need to insert or remove elements in
1192    /// the tree.
1193    #[inline]
1194    #[allow(clippy::should_implement_trait)]
1195    pub fn into_iter(self) -> Iter<'a, K, V, A> {
1196        let (node, pos) = self.raw.stack[Height::leaf()];
1197        Iter {
1198            raw: crate::RawIter { node, pos },
1199            btree: self.raw.btree,
1200        }
1201    }
1202
1203    /// Returns a mutable iterator starting a the current element.
1204    ///
1205    /// Unlike [`CursorMut::iter_mut`] the returned iterator has the same lifetime
1206    /// as the cursor and consumes the cursor.
1207    ///
1208    /// Iterators are more efficient than cursors. Prefer using them if you don't
1209    /// need reverse iteration or if you don't need to insert or remove elements in
1210    /// the tree.
1211    #[inline]
1212    pub fn into_iter_mut(self) -> IterMut<'a, K, V, A> {
1213        let (node, pos) = self.raw.stack[Height::leaf()];
1214        IterMut {
1215            raw: crate::RawIter { node, pos },
1216            btree: self.raw.btree,
1217        }
1218    }
1219
1220    /// Inserts `key` and `value` before the element that the cursor is
1221    /// currently pointing to.
1222    ///
1223    /// After insertion the cursor will be pointing to the newly inserted
1224    /// element.
1225    ///
1226    /// If the cursor is pointing to the end of the tree then this inserts the
1227    /// new element at the end of the tree after all other elements.
1228    ///
1229    /// It is the user's responsibility to ensure that inserting `key` at this
1230    /// position does not violate the invariant that all keys must be in sorted
1231    /// order in the tree. Violating this invariant is safe but may cause
1232    /// other operations to return incorrect results or panic.
1233    #[inline]
1234    pub fn insert_before(&mut self, key: K, value: V) {
1235        self.raw.insert::<false>(key, value);
1236    }
1237
1238    /// Inserts `key` and `value` after the element that the cursor is
1239    /// currently pointing to.
1240    ///
1241    /// After insertion the cursor will still be pointing to the same element as
1242    /// before the insertion.
1243    ///
1244    /// It is the user's responsibility to ensure that inserting `key` at this
1245    /// position does not violate the invariant that all keys must be in sorted
1246    /// order in the tree. Violating this invariant is safe but may cause
1247    /// other operations to return incorrect results or panic.
1248    ///
1249    /// # Panics
1250    ///
1251    /// Panics if the cursor is pointing to the end of the tree.
1252    #[inline]
1253    pub fn insert_after(&mut self, key: K, value: V) {
1254        self.raw.insert::<true>(key, value);
1255    }
1256
1257    /// Replaces the key and value of the element that the cursor is currently
1258    /// pointing to and returns the previous key and value.
1259    ///
1260    /// It is the user's responsibility to ensure that inserting `key` at this
1261    /// position does not violate the invariant that all keys must be in sorted
1262    /// order in the tree. Violating this invariant is safe but may cause
1263    /// other operations to return incorrect results or panic.
1264    ///
1265    /// # Panics
1266    ///
1267    /// Panics if the cursor is pointing to the end of the tree.
1268    #[inline]
1269    pub fn replace(&mut self, key: K, value: V) -> (K, V) {
1270        self.raw.replace(key, value)
1271    }
1272
1273    /// Removes the element that the cursor is currently pointing to and returns
1274    /// it.
1275    ///
1276    /// After removal the cursor will point to the element after the current
1277    /// one.
1278    ///
1279    /// # Panics
1280    ///
1281    /// Panics if the cursor is pointing to the end of the tree.
1282    #[inline]
1283    pub fn remove(&mut self) -> (K, V) {
1284        self.raw.remove()
1285    }
1286}
1287
1288impl<K: BTreeKey, V, A: Allocator> BTree<K, V, A> {
1289    /// Returns a [`RawCursor`] pointing at the first element of the tree.
1290    #[inline]
1291    fn raw_cursor<Ref: Deref<Target = Self>>(btree: Ref) -> RawCursor<K, V, A, Ref> {
1292        let mut stack = <K::Int as BTreeInteger>::Stack::default();
1293
1294        // Go down the tree, at each internal node selecting the first sub-tree.
1295        let mut height = btree.height;
1296        let mut node = btree.root;
1297        while let Some(down) = height.down() {
1298            stack[height] = (node, pos!(0));
1299            node = unsafe { node.value(pos!(0), &btree.internal).assume_init_read() };
1300            height = down;
1301        }
1302
1303        // The first leaf node is always the left-most leaf on the tree and is
1304        // never deleted.
1305        debug_assert_eq!(node, NodeRef::zero());
1306        stack[height] = (NodeRef::zero(), pos!(0));
1307        RawCursor { stack, btree }
1308    }
1309
1310    /// Returns a [`RawCursor`] pointing at the first element with key greater
1311    /// than `bound`.
1312    #[inline]
1313    fn raw_cursor_at<Ref: Deref<Target = Self>>(
1314        btree: Ref,
1315        key: <K::Int as BTreeInteger>::Raw,
1316    ) -> RawCursor<K, V, A, Ref> {
1317        let stack = <K::Int as BTreeInteger>::Stack::default();
1318        let mut cursor = RawCursor { stack, btree };
1319        cursor.seek(key);
1320        cursor
1321    }
1322
1323    /// Returns a [`Cursor`] pointing at the first element of the tree.
1324    #[inline]
1325    pub fn cursor(&self) -> Cursor<'_, K, V, A> {
1326        let raw = Self::raw_cursor(self);
1327        Cursor { raw }
1328    }
1329
1330    /// Returns a [`Cursor`] pointing at the first element with key greater
1331    /// than `bound`.
1332    #[inline]
1333    pub fn cursor_at(&self, bound: Bound<K>) -> Cursor<'_, K, V, A> {
1334        let key = match bound {
1335            Bound::Included(key) => int_from_key(key),
1336            Bound::Excluded(key) => K::Int::increment(int_from_key(key)),
1337            Bound::Unbounded => K::Int::MAX,
1338        };
1339        let raw = Self::raw_cursor_at(self, key);
1340        Cursor { raw }
1341    }
1342
1343    /// Returns a [`CursorMut`] pointing at the first element of the tree.
1344    #[inline]
1345    pub fn cursor_mut(&mut self) -> CursorMut<'_, K, V, A> {
1346        let raw = Self::raw_cursor(self);
1347        CursorMut { raw }
1348    }
1349
1350    /// Returns a [`CursorMut`] pointing at the first element with key greater
1351    /// than `bound`.
1352    #[inline]
1353    pub fn cursor_mut_at(&mut self, bound: Bound<K>) -> CursorMut<'_, K, V, A> {
1354        let key = match bound {
1355            Bound::Included(key) => int_from_key(key),
1356            Bound::Excluded(key) => K::Int::increment(int_from_key(key)),
1357            Bound::Unbounded => K::Int::MAX,
1358        };
1359        let raw = Self::raw_cursor_at(self, key);
1360        CursorMut { raw }
1361    }
1362}