Skip to main content

alloc/collections/btree/
node.rs

1// This is an attempt at an implementation following the ideal
2//
3// ```
4// struct BTreeMap<K, V> {
5//     height: usize,
6//     root: Option<Box<Node<K, V, height>>>
7// }
8//
9// struct Node<K, V, height: usize> {
10//     keys: [K; 2 * B - 1],
11//     vals: [V; 2 * B - 1],
12//     edges: [if height > 0 { Box<Node<K, V, height - 1>> } else { () }; 2 * B],
13//     parent: Option<(NonNull<Node<K, V, height + 1>>, u16)>,
14//     len: u16,
15// }
16// ```
17//
18// Since Rust doesn't actually have dependent types and polymorphic recursion,
19// we make do with lots of unsafety.
20
21// A major goal of this module is to avoid complexity by treating the tree as a generic (if
22// weirdly shaped) container and avoiding dealing with most of the B-Tree invariants. As such,
23// this module doesn't care whether the entries are sorted, which nodes can be underfull, or
24// even what underfull means. However, we do rely on a few invariants:
25//
26// - Trees must have uniform depth/height. This means that every path down to a leaf from a
27//   given node has exactly the same length.
28// - A node of length `n` has `n` keys, `n` values, and `n + 1` edges.
29//   This implies that even an empty node has at least one edge.
30//   For a leaf node, "having an edge" only means we can identify a position in the node,
31//   since leaf edges are empty and need no data representation. In an internal node,
32//   an edge both identifies a position and contains a pointer to a child node.
33
34use core::marker::PhantomData;
35use core::mem::{self, DropGuard, MaybeUninit};
36use core::num::NonZero;
37use core::ptr::{self, NonNull};
38use core::slice::SliceIndex;
39
40use crate::alloc::{Allocator, AllocatorClone, Layout};
41use crate::boxed::Box;
42
43const B: usize = 6;
44pub(super) const CAPACITY: usize = 2 * B - 1;
45pub(super) const MIN_LEN_AFTER_SPLIT: usize = B - 1;
46const KV_IDX_CENTER: usize = B - 1;
47const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1;
48const EDGE_IDX_RIGHT_OF_CENTER: usize = B;
49
50/// The underlying representation of leaf nodes and part of the representation of internal nodes.
51struct LeafNode<K, V> {
52    /// We want to be covariant in `K` and `V`.
53    parent: Option<NonNull<InternalNode<K, V>>>,
54
55    /// This node's index into the parent node's `edges` array.
56    /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`.
57    /// This is only guaranteed to be initialized when `parent` is non-null.
58    parent_idx: MaybeUninit<u16>,
59
60    /// The number of keys and values this node stores.
61    len: u16,
62
63    /// The arrays storing the actual data of the node. Only the first `len` elements of each
64    /// array are initialized and valid.
65    keys: [MaybeUninit<K>; CAPACITY],
66    vals: [MaybeUninit<V>; CAPACITY],
67}
68
69impl<K, V> LeafNode<K, V> {
70    /// Initializes a new `LeafNode` in-place.
71    ///
72    /// # Safety
73    ///
74    /// The caller must ensure that `this` points to a (possibly uninitialized) `LeafNode`
75    unsafe fn init(this: *mut Self) {
76        // As a general policy, we leave fields uninitialized if they can be, as this should
77        // be both slightly faster and easier to track in Valgrind.
78        // ignore-tidy-undocumented-unsafe
79        unsafe {
80            // parent_idx, keys, and vals are all MaybeUninit
81            (&raw mut (*this).parent).write(None);
82            (&raw mut (*this).len).write(0);
83        }
84    }
85
86    /// Creates a new boxed `LeafNode`.
87    fn new<A: AllocatorClone>(alloc: A) -> Box<Self, A> {
88        let mut leaf = Box::new_uninit_in(alloc);
89
90        // SAFETY: `leaf` points to a `LeafNode`.
91        unsafe { LeafNode::init(leaf.as_mut_ptr()) };
92        // SAFETY: `leaf` was just initialized.
93        unsafe { leaf.assume_init() }
94    }
95}
96
97/// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden
98/// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an
99/// `InternalNode` can be directly cast to a pointer to the underlying `LeafNode` portion of the
100/// node, allowing code to act on leaf and internal nodes generically without having to even check
101/// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`.
102#[repr(C)]
103// gdb_providers.py uses this type name for introspection.
104struct InternalNode<K, V> {
105    data: LeafNode<K, V>,
106
107    /// The pointers to the children of this node. `len + 1` of these are considered
108    /// initialized and valid, except that near the end, while the tree is held
109    /// through borrow type `Dying`, some of these pointers are dangling.
110    edges: [MaybeUninit<BoxedNode<K, V>>; 2 * B],
111}
112
113impl<K, V> InternalNode<K, V> {
114    /// Creates a new boxed `InternalNode`.
115    ///
116    /// # Safety
117    /// An invariant of internal nodes is that they have at least one
118    /// initialized and valid edge. This function does not set up
119    /// such an edge.
120    unsafe fn new<A: AllocatorClone>(alloc: A) -> Box<Self, A> {
121        let mut node = Box::<Self, _>::new_uninit_in(alloc);
122
123        // SAFETY: argument points to the `node.data` `LeafNode`.
124        unsafe { LeafNode::init(&raw mut (*node.as_mut_ptr()).data) };
125        // SAFETY: `node.data` was just initialized and `node.edges` is MaybeUninit.
126        unsafe { node.assume_init() }
127    }
128}
129
130/// A managed, non-null pointer to a node. This is either an owned pointer to
131/// `LeafNode<K, V>` or an owned pointer to `InternalNode<K, V>`.
132///
133/// However, `BoxedNode` contains no information as to which of the two types
134/// of nodes it actually contains, and, partially due to this lack of information,
135/// is not a separate type and has no destructor.
136type BoxedNode<K, V> = NonNull<LeafNode<K, V>>;
137
138// N.B. `NodeRef` is always covariant in `K` and `V`, even when the `BorrowType`
139// is `Mut`. This is technically wrong, but cannot result in any unsafety due to
140// internal use of `NodeRef` because we stay completely generic over `K` and `V`.
141// However, whenever a public type wraps `NodeRef`, make sure that it has the
142// correct variance.
143///
144/// A reference to a node.
145///
146/// This type has a number of parameters that control how it acts:
147/// - `BorrowType`: A dummy type that describes the kind of borrow and carries a lifetime.
148///    - When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`.
149///    - When this is `ValMut<'a>`, the `NodeRef` acts roughly like `&'a Node`
150///      with respect to keys and tree structure, but also allows many
151///      mutable references to values throughout the tree to coexist.
152///    - When this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`,
153///      although insert methods allow a mutable pointer to a value to coexist.
154///    - When this is `Owned`, the `NodeRef` acts roughly like `Box<Node>`,
155///      but does not have a destructor, and must be cleaned up manually.
156///    - When this is `Dying`, the `NodeRef` still acts roughly like `Box<Node>`,
157///      but has methods to destroy the tree bit by bit, and ordinary methods,
158///      while not marked as unsafe to call, can invoke UB if called incorrectly.
159///   Since any `NodeRef` allows navigating through the tree, `BorrowType`
160///   effectively applies to the entire tree, not just to the node itself.
161/// - `K` and `V`: These are the types of keys and values stored in the nodes.
162/// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is
163///   `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the
164///   `NodeRef` points to an internal node, and when this is `LeafOrInternal` the
165///   `NodeRef` could be pointing to either type of node.
166///   `Type` is named `NodeType` when used outside `NodeRef`.
167///
168/// Both `BorrowType` and `NodeType` restrict what methods we implement, to
169/// exploit static type safety. There are limitations in the way we can apply
170/// such restrictions:
171/// - For each type parameter, we can only define a method either generically
172///   or for one particular type. For example, we cannot define a method like
173///   `into_kv` generically for all `BorrowType`, or once for all types that
174///   carry a lifetime, because we want it to return `&'a` references.
175///   Therefore, we define it only for the least powerful type `Immut<'a>`.
176/// - We cannot get implicit coercion from say `Mut<'a>` to `Immut<'a>`.
177///   Therefore, we have to explicitly call `reborrow` on a more powerful
178///   `NodeRef` in order to reach a method like `into_kv`.
179///
180/// All methods on `NodeRef` that return some kind of reference, either:
181/// - Take `self` by value, and return the lifetime carried by `BorrowType`.
182///   Sometimes, to invoke such a method, we need to call `reborrow_mut`.
183/// - Take `self` by reference, and (implicitly) return that reference's
184///   lifetime, instead of the lifetime carried by `BorrowType`. That way,
185///   the borrow checker guarantees that the `NodeRef` remains borrowed as long
186///   as the returned reference is used.
187///   The methods supporting insert bend this rule by returning a raw pointer,
188///   i.e., a reference without any lifetime.
189pub(super) struct NodeRef<BorrowType, K, V, Type> {
190    /// The number of levels that the node and the level of leaves are apart, a
191    /// constant of the node that cannot be entirely described by `Type`, and that
192    /// the node itself does not store. We only need to store the height of the root
193    /// node, and derive every other node's height from it.
194    /// Must be zero if `Type` is `Leaf` and non-zero if `Type` is `Internal`.
195    height: usize,
196    /// The pointer to the leaf or internal node. The definition of `InternalNode`
197    /// ensures that the pointer is valid either way.
198    node: NonNull<LeafNode<K, V>>,
199    _marker: PhantomData<(BorrowType, Type)>,
200}
201
202/// The root node of an owned tree.
203///
204/// Note that this does not have a destructor, and must be cleaned up manually.
205pub(super) type Root<K, V> = NodeRef<marker::Owned, K, V, marker::LeafOrInternal>;
206
207impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> {}
208impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
209    fn clone(&self) -> Self {
210        *self
211    }
212}
213
214unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync for NodeRef<BorrowType, K, V, Type> {}
215
216unsafe impl<K: Sync, V: Sync, Type> Send for NodeRef<marker::Immut<'_>, K, V, Type> {}
217unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Mut<'_>, K, V, Type> {}
218unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::ValMut<'_>, K, V, Type> {}
219unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Owned, K, V, Type> {}
220unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Dying, K, V, Type> {}
221
222impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
223    pub(super) fn new_leaf<A: AllocatorClone>(alloc: A) -> Self {
224        Self::from_new_leaf(LeafNode::new(alloc))
225    }
226
227    fn from_new_leaf<A: AllocatorClone>(leaf: Box<LeafNode<K, V>, A>) -> Self {
228        // The allocator must be dropped, not leaked.  See also `BTreeMap::alloc`.
229        let (node, _alloc) = Box::into_non_null_with_allocator(leaf);
230        NodeRef { height: 0, node, _marker: PhantomData }
231    }
232}
233
234impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
235    /// Creates a new internal (height > 0) `NodeRef`
236    fn new_internal<A: AllocatorClone>(child: Root<K, V>, alloc: A) -> Self {
237        // ignore-tidy-undocumented-unsafe
238        let mut new_node = unsafe { InternalNode::new(alloc) };
239        new_node.edges[0].write(child.node);
240        NodeRef::from_new_internal(new_node, NonZero::new(child.height + 1).unwrap())
241    }
242
243    /// Creates a new internal (height > 0) `NodeRef` from an existing internal node
244    fn from_new_internal<A: AllocatorClone>(
245        internal: Box<InternalNode<K, V>, A>,
246        height: NonZero<usize>,
247    ) -> Self {
248        // The allocator must be dropped, not leaked.  See also `BTreeMap::alloc`.
249        let (node, _alloc) = Box::into_non_null_with_allocator(internal);
250        let mut this = NodeRef { height: height.into(), node: node.cast(), _marker: PhantomData };
251        this.borrow_mut().correct_all_childrens_parent_links();
252        this
253    }
254}
255
256impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
257    /// Unpack a node reference that was packed as `NodeRef::parent`.
258    fn from_internal(node: NonNull<InternalNode<K, V>>, height: usize) -> Self {
259        if true {
    if !(height > 0) {
        ::core::panicking::panic("assertion failed: height > 0")
    };
};debug_assert!(height > 0);
260        NodeRef { height, node: node.cast(), _marker: PhantomData }
261    }
262}
263
264impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
265    /// Exposes the data of an internal node.
266    ///
267    /// Returns a raw ptr to avoid invalidating other references to this node.
268    fn as_internal_ptr(this: &Self) -> *mut InternalNode<K, V> {
269        // SAFETY: the static node type is `Internal`.
270        this.node.as_ptr() as *mut InternalNode<K, V>
271    }
272}
273
274impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
275    /// Borrows exclusive access to the data of an internal node.
276    fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
277        let ptr = Self::as_internal_ptr(self);
278        // ignore-tidy-undocumented-unsafe
279        unsafe { &mut *ptr }
280    }
281}
282
283impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
284    /// Finds the length of the node. This is the number of keys or values.
285    /// The number of edges is `len() + 1`.
286    /// Note that, despite being safe, calling this function can have the side effect
287    /// of invalidating mutable references that unsafe code has created.
288    pub(super) fn len(&self) -> usize {
289        // SAFETY: We only access the `len` field here. If BorrowType is marker::ValMut,
290        // there might be outstanding mutable references to values that we must not invalidate.
291        unsafe { usize::from((*Self::as_leaf_ptr(self)).len) }
292    }
293
294    /// Returns the number of levels that the node and leaves are apart. Zero
295    /// height means the node is a leaf itself. If you picture trees with the
296    /// root on top, the number says at which elevation the node appears.
297    /// If you picture trees with leaves on top, the number says how high
298    /// the tree extends above the node.
299    pub(super) fn height(&self) -> usize {
300        self.height
301    }
302
303    /// Temporarily takes out another, immutable reference to the same node.
304    pub(super) fn reborrow(&self) -> NodeRef<marker::Immut<'_>, K, V, Type> {
305        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
306    }
307
308    /// Exposes the leaf portion of any leaf or internal node.
309    ///
310    /// Returns a raw ptr to avoid invalidating other references to this node.
311    fn as_leaf_ptr(this: &Self) -> *mut LeafNode<K, V> {
312        // The node must be valid for at least the LeafNode portion.
313        // This is not a reference in the NodeRef type because we don't know if
314        // it should be unique or shared.
315        this.node.as_ptr()
316    }
317}
318
319impl<BorrowType: marker::BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
320    /// Finds the parent of the current node. Returns `Ok(handle)` if the current
321    /// node actually has a parent, where `handle` points to the edge of the parent
322    /// that points to the current node. Returns `Err(self)` if the current node has
323    /// no parent, giving back the original `NodeRef`.
324    ///
325    /// The method name assumes you picture trees with the root node on top.
326    ///
327    /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
328    /// both, upon success, do nothing.
329    pub(super) fn ascend(
330        self,
331    ) -> Result<Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>, Self> {
332        const {
333            if !BorrowType::TRAVERSAL_PERMIT {
    ::core::panicking::panic("assertion failed: BorrowType::TRAVERSAL_PERMIT")
};assert!(BorrowType::TRAVERSAL_PERMIT);
334        }
335
336        // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut,
337        // there might be outstanding mutable references to values that we must not invalidate.
338        let leaf_ptr: *const _ = Self::as_leaf_ptr(&self);
339        // ignore-tidy-undocumented-unsafe
340        unsafe { (*leaf_ptr).parent }
341            .as_ref()
342            .map(|parent| Handle {
343                node: NodeRef::from_internal(*parent, self.height + 1),
344                // ignore-tidy-undocumented-unsafe
345                idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) },
346                _marker: PhantomData,
347            })
348            .ok_or(self)
349    }
350
351    pub(super) fn first_edge(self) -> Handle<Self, marker::Edge> {
352        // ignore-tidy-undocumented-unsafe
353        unsafe { Handle::new_edge(self, 0) }
354    }
355
356    pub(super) fn last_edge(self) -> Handle<Self, marker::Edge> {
357        let len = self.len();
358        // ignore-tidy-undocumented-unsafe
359        unsafe { Handle::new_edge(self, len) }
360    }
361
362    /// Note that `self` must be nonempty.
363    pub(super) fn first_kv(self) -> Handle<Self, marker::KV> {
364        let len = self.len();
365        if !(len > 0) { ::core::panicking::panic("assertion failed: len > 0") };assert!(len > 0);
366        // ignore-tidy-undocumented-unsafe
367        unsafe { Handle::new_kv(self, 0) }
368    }
369
370    /// Note that `self` must be nonempty.
371    pub(super) fn last_kv(self) -> Handle<Self, marker::KV> {
372        let len = self.len();
373        if !(len > 0) { ::core::panicking::panic("assertion failed: len > 0") };assert!(len > 0);
374        // ignore-tidy-undocumented-unsafe
375        unsafe { Handle::new_kv(self, len - 1) }
376    }
377}
378
379impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
380    /// Could be a public implementation of PartialEq, but only used in this module.
381    fn eq(&self, other: &Self) -> bool {
382        let Self { node, height, _marker } = self;
383        if node.eq(&other.node) {
384            if true {
    {
        match (&*height, &other.height) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(*height, other.height);
385            true
386        } else {
387            false
388        }
389    }
390}
391
392impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
393    /// Exposes the leaf portion of any leaf or internal node in an immutable tree.
394    fn into_leaf(self) -> &'a LeafNode<K, V> {
395        let ptr = Self::as_leaf_ptr(&self);
396        // SAFETY: there can be no mutable references into this tree borrowed as `Immut`.
397        unsafe { &*ptr }
398    }
399
400    /// Borrows a view into the keys stored in the node.
401    pub(super) fn keys(&self) -> &[K] {
402        let leaf = self.into_leaf();
403        // ignore-tidy-undocumented-unsafe
404        unsafe { leaf.keys.get_unchecked(..usize::from(leaf.len)).assume_init_ref() }
405    }
406}
407
408impl<K, V> NodeRef<marker::Dying, K, V, marker::LeafOrInternal> {
409    /// Similar to `ascend`, gets a reference to a node's parent node, but also
410    /// deallocates the current node in the process. This is unsafe because the
411    /// current node will still be accessible despite being deallocated.
412    pub(super) unsafe fn deallocate_and_ascend<A: AllocatorClone>(
413        self,
414        alloc: A,
415    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::Internal>, marker::Edge>> {
416        let height = self.height;
417        let node = self.node;
418        let ret = self.ascend().ok();
419        // ignore-tidy-undocumented-unsafe
420        unsafe {
421            alloc.deallocate(
422                node.cast(),
423                if height > 0 {
424                    Layout::new::<InternalNode<K, V>>()
425                } else {
426                    Layout::new::<LeafNode<K, V>>()
427                },
428            );
429        }
430        ret
431    }
432}
433
434impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
435    /// Temporarily takes out another mutable reference to the same node. Beware, as
436    /// this method is very dangerous, doubly so since it might not immediately appear
437    /// dangerous.
438    ///
439    /// Because mutable pointers can roam anywhere around the tree, the returned
440    /// pointer can easily be used to make the original pointer dangling, out of
441    /// bounds, or invalid under stacked borrow rules.
442    // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef`
443    // that restricts the use of navigation methods on reborrowed pointers,
444    // preventing this unsafety.
445    unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
446        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
447    }
448
449    /// Borrows exclusive access to the leaf portion of a leaf or internal node.
450    fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
451        let ptr = Self::as_leaf_ptr(self);
452        // SAFETY: we have exclusive access to the entire node.
453        unsafe { &mut *ptr }
454    }
455
456    /// Offers exclusive access to the leaf portion of a leaf or internal node.
457    fn into_leaf_mut(mut self) -> &'a mut LeafNode<K, V> {
458        let ptr = Self::as_leaf_ptr(&mut self);
459        // SAFETY: we have exclusive access to the entire node.
460        unsafe { &mut *ptr }
461    }
462
463    /// Returns a dormant copy of this node with its lifetime erased which can
464    /// be reawakened later.
465    pub(super) fn dormant(&self) -> NodeRef<marker::DormantMut, K, V, Type> {
466        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
467    }
468}
469
470impl<K, V, Type> NodeRef<marker::DormantMut, K, V, Type> {
471    /// Revert to the unique borrow initially captured.
472    ///
473    /// # Safety
474    ///
475    /// The reborrow must have ended, i.e., the reference returned by `new` and
476    /// all pointers and references derived from it, must not be used anymore.
477    pub(super) unsafe fn awaken<'a>(self) -> NodeRef<marker::Mut<'a>, K, V, Type> {
478        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
479    }
480}
481
482impl<K, V, Type> NodeRef<marker::Dying, K, V, Type> {
483    /// Borrows exclusive access to the leaf portion of a dying leaf or internal node.
484    fn as_leaf_dying(&mut self) -> &mut LeafNode<K, V> {
485        let ptr = Self::as_leaf_ptr(self);
486        // SAFETY: we have exclusive access to the entire node.
487        unsafe { &mut *ptr }
488    }
489}
490
491impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
492    /// Borrows exclusive access to an element of the key storage area.
493    ///
494    /// # Safety
495    /// `index` is in bounds of 0..CAPACITY
496    unsafe fn key_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
497    where
498        I: SliceIndex<[MaybeUninit<K>], Output = Output>,
499    {
500        // SAFETY: the caller will not be able to call further methods on self
501        // until the key slice reference is dropped, as we have unique access
502        // for the lifetime of the borrow.
503        unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) }
504    }
505
506    /// Borrows exclusive access to an element or slice of the node's value storage area.
507    ///
508    /// # Safety
509    /// `index` is in bounds of 0..CAPACITY
510    unsafe fn val_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
511    where
512        I: SliceIndex<[MaybeUninit<V>], Output = Output>,
513    {
514        // SAFETY: the caller will not be able to call further methods on self
515        // until the value slice reference is dropped, as we have unique access
516        // for the lifetime of the borrow.
517        unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) }
518    }
519}
520
521impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
522    /// Borrows exclusive access to an element or slice of the node's storage area for edge contents.
523    ///
524    /// # Safety
525    /// `index` is in bounds of 0..CAPACITY + 1
526    unsafe fn edge_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
527    where
528        I: SliceIndex<[MaybeUninit<BoxedNode<K, V>>], Output = Output>,
529    {
530        // SAFETY: the caller will not be able to call further methods on self
531        // until the edge slice reference is dropped, as we have unique access
532        // for the lifetime of the borrow.
533        unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) }
534    }
535}
536
537impl<'a, K, V, Type> NodeRef<marker::ValMut<'a>, K, V, Type> {
538    /// # Safety
539    /// - The node has more than `idx` initialized elements.
540    unsafe fn into_key_val_mut_at(mut self, idx: usize) -> (&'a K, &'a mut V) {
541        // We only create a reference to the one element we are interested in,
542        // to avoid aliasing with outstanding references to other elements,
543        // in particular, those returned to the caller in earlier iterations.
544        let leaf = Self::as_leaf_ptr(&mut self);
545        // ignore-tidy-undocumented-unsafe
546        let keys = unsafe { &raw const (*leaf).keys };
547        // ignore-tidy-undocumented-unsafe
548        let vals = unsafe { &raw mut (*leaf).vals };
549        // We must coerce to unsized array pointers because of Rust issue #74679.
550        let keys: *const [_] = keys;
551        let vals: *mut [_] = vals;
552        // ignore-tidy-undocumented-unsafe
553        let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() };
554        // ignore-tidy-undocumented-unsafe
555        let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() };
556        (key, val)
557    }
558}
559
560impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
561    /// Borrows exclusive access to the length of the node.
562    pub(super) fn len_mut(&mut self) -> &mut u16 {
563        &mut self.as_leaf_mut().len
564    }
565}
566
567impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
568    /// # Safety
569    /// Every item returned by `range` is a valid edge index for the node.
570    unsafe fn correct_childrens_parent_links<R: Iterator<Item = usize>>(&mut self, range: R) {
571        for i in range {
572            if true {
    if !(i <= self.len()) {
        ::core::panicking::panic("assertion failed: i <= self.len()")
    };
};debug_assert!(i <= self.len());
573            // ignore-tidy-undocumented-unsafe
574            unsafe { Handle::new_edge(self.reborrow_mut(), i) }.correct_parent_link();
575        }
576    }
577
578    fn correct_all_childrens_parent_links(&mut self) {
579        let len = self.len();
580        // ignore-tidy-undocumented-unsafe
581        unsafe { self.correct_childrens_parent_links(0..=len) };
582    }
583}
584
585impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
586    /// Sets the node's link to its parent edge,
587    /// without invalidating other references to the node.
588    fn set_parent_link(&mut self, parent: NonNull<InternalNode<K, V>>, parent_idx: usize) {
589        let leaf = Self::as_leaf_ptr(self);
590        // ignore-tidy-undocumented-unsafe
591        unsafe { (*leaf).parent = Some(parent) };
592        // ignore-tidy-undocumented-unsafe
593        unsafe { (*leaf).parent_idx.write(parent_idx as u16) };
594    }
595}
596
597impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
598    /// Clears the root's link to its parent edge.
599    fn clear_parent_link(&mut self) {
600        let mut root_node = self.borrow_mut();
601        let leaf = root_node.as_leaf_mut();
602        leaf.parent = None;
603    }
604}
605
606impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
607    /// Returns a new owned tree, with its own root node that is initially empty.
608    pub(super) fn new<A: AllocatorClone>(alloc: A) -> Self {
609        NodeRef::new_leaf(alloc).forget_type()
610    }
611
612    /// Adds a new internal node with a single edge pointing to the previous root node,
613    /// make that new node the root node, and return it. This increases the height by 1
614    /// and is the opposite of `pop_internal_level`.
615    pub(super) fn push_internal_level<A: AllocatorClone>(
616        &mut self,
617        alloc: A,
618    ) -> NodeRef<marker::Mut<'_>, K, V, marker::Internal> {
619        super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root, alloc).forget_type());
620
621        // `self.borrow_mut()`, except that we just forgot we're internal now:
622        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
623    }
624
625    /// Removes the internal root node, using its first child as the new root node.
626    /// As it is intended only to be called when the root node has only one child,
627    /// no cleanup is done on any of the keys, values and other children.
628    /// This decreases the height by 1 and is the opposite of `push_internal_level`.
629    ///
630    /// Does not invalidate any handles or references pointing into the subtree
631    /// rooted at the first child of `self`.
632    ///
633    /// Panics if there is no internal level, i.e., if the root node is a leaf.
634    pub(super) fn pop_internal_level<A: AllocatorClone>(&mut self, alloc: A) {
635        if !(self.height > 0) {
    ::core::panicking::panic("assertion failed: self.height > 0")
};assert!(self.height > 0);
636
637        let top = self.node;
638
639        // SAFETY: we asserted to be internal.
640        let mut internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() };
641        let internal_node = internal_self.as_internal_mut();
642        // SAFETY: the first edge is always initialized.
643        self.node = unsafe { internal_node.edges[0].assume_init_read() };
644        self.height -= 1;
645        self.clear_parent_link();
646
647        // ignore-tidy-undocumented-unsafe
648        unsafe {
649            alloc.deallocate(top.cast(), Layout::new::<InternalNode<K, V>>());
650        }
651    }
652}
653
654impl<K, V, Type> NodeRef<marker::Owned, K, V, Type> {
655    /// Mutably borrows the owned root node. Unlike `reborrow_mut`, this is safe
656    /// because the return value cannot be used to destroy the root, and there
657    /// cannot be other references to the tree.
658    pub(super) fn borrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
659        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
660    }
661
662    /// Slightly mutably borrows the owned root node.
663    pub(super) fn borrow_valmut(&mut self) -> NodeRef<marker::ValMut<'_>, K, V, Type> {
664        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
665    }
666
667    /// Irreversibly transitions to a reference that permits traversal and offers
668    /// destructive methods and little else.
669    pub(super) fn into_dying(self) -> NodeRef<marker::Dying, K, V, Type> {
670        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
671    }
672}
673
674impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
675    /// Adds a key-value pair to the end of the node, and returns
676    /// a handle to the inserted value.
677    ///
678    /// # Safety
679    ///
680    /// The returned handle has an unbound lifetime.
681    pub(super) unsafe fn push_with_handle<'b>(
682        &mut self,
683        key: K,
684        val: V,
685    ) -> Handle<NodeRef<marker::Mut<'b>, K, V, marker::Leaf>, marker::KV> {
686        let len = self.len_mut();
687        let idx = usize::from(*len);
688        if !(idx < CAPACITY) {
    ::core::panicking::panic("assertion failed: idx < CAPACITY")
};assert!(idx < CAPACITY);
689        *len += 1;
690        // ignore-tidy-undocumented-unsafe
691        unsafe {
692            self.key_area_mut(idx).write(key);
693            self.val_area_mut(idx).write(val);
694            Handle::new_kv(
695                NodeRef { height: self.height, node: self.node, _marker: PhantomData },
696                idx,
697            )
698        }
699    }
700
701    /// Adds a key-value pair to the end of the node, and returns
702    /// the mutable reference of the inserted value.
703    pub(super) fn push(&mut self, key: K, val: V) -> *mut V {
704        // SAFETY: The unbound handle is no longer accessible.
705        unsafe { self.push_with_handle(key, val).into_val_mut() }
706    }
707}
708
709impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
710    /// Adds a key-value pair, and an edge to go to the right of that pair,
711    /// to the end of the node.
712    pub(super) fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
713        if !(edge.height == self.height - 1) {
    ::core::panicking::panic("assertion failed: edge.height == self.height - 1")
};assert!(edge.height == self.height - 1);
714
715        let len = self.len_mut();
716        let idx = usize::from(*len);
717        if !(idx < CAPACITY) {
    ::core::panicking::panic("assertion failed: idx < CAPACITY")
};assert!(idx < CAPACITY);
718        *len += 1;
719        // ignore-tidy-undocumented-unsafe
720        unsafe {
721            self.key_area_mut(idx).write(key);
722            self.val_area_mut(idx).write(val);
723            self.edge_area_mut(idx + 1).write(edge.node);
724            Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
725        }
726    }
727}
728
729impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Leaf> {
730    /// Removes any static information asserting that this node is a `Leaf` node.
731    pub(super) fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
732        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
733    }
734}
735
736impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
737    /// Removes any static information asserting that this node is an `Internal` node.
738    pub(super) fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
739        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
740    }
741}
742
743impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
744    /// Checks whether a node is an `Internal` node or a `Leaf` node.
745    pub(super) fn force(
746        self,
747    ) -> ForceResult<
748        NodeRef<BorrowType, K, V, marker::Leaf>,
749        NodeRef<BorrowType, K, V, marker::Internal>,
750    > {
751        if self.height == 0 {
752            ForceResult::Leaf(NodeRef {
753                height: self.height,
754                node: self.node,
755                _marker: PhantomData,
756            })
757        } else {
758            ForceResult::Internal(NodeRef {
759                height: self.height,
760                node: self.node,
761                _marker: PhantomData,
762            })
763        }
764    }
765}
766
767impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
768    /// Unsafely asserts to the compiler the static information that this node is a `Leaf`.
769    pub(super) unsafe fn cast_to_leaf_unchecked(
770        self,
771    ) -> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
772        if true {
    if !(self.height == 0) {
        ::core::panicking::panic("assertion failed: self.height == 0")
    };
};debug_assert!(self.height == 0);
773        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
774    }
775
776    /// Unsafely asserts to the compiler the static information that this node is an `Internal`.
777    unsafe fn cast_to_internal_unchecked(self) -> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
778        if true {
    if !(self.height > 0) {
        ::core::panicking::panic("assertion failed: self.height > 0")
    };
};debug_assert!(self.height > 0);
779        NodeRef { height: self.height, node: self.node, _marker: PhantomData }
780    }
781}
782
783/// A reference to a specific key-value pair or edge within a node. The `Node` parameter
784/// must be a `NodeRef`, while the `Type` can either be `KV` (signifying a handle on a key-value
785/// pair) or `Edge` (signifying a handle on an edge).
786///
787/// Note that even `Leaf` nodes can have `Edge` handles. Instead of representing a pointer to
788/// a child node, these represent the spaces where child pointers would go between the key-value
789/// pairs. For example, in a node with length 2, there would be 3 possible edge locations - one
790/// to the left of the node, one between the two pairs, and one at the right of the node.
791pub(super) struct Handle<Node, Type> {
792    node: Node,
793    idx: usize,
794    _marker: PhantomData<Type>,
795}
796
797impl<Node: Copy, Type> Copy for Handle<Node, Type> {}
798// We don't need the full generality of `#[derive(Clone)]`, as the only time `Node` will be
799// `Clone`able is when it is an immutable reference and therefore `Copy`.
800impl<Node: Copy, Type> Clone for Handle<Node, Type> {
801    fn clone(&self) -> Self {
802        *self
803    }
804}
805
806impl<Node, Type> Handle<Node, Type> {
807    /// Retrieves the node that contains the edge or key-value pair this handle points to.
808    pub(super) fn into_node(self) -> Node {
809        self.node
810    }
811
812    /// Returns the position of this handle in the node.
813    pub(super) fn idx(&self) -> usize {
814        self.idx
815    }
816}
817
818impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
819    /// Creates a new handle to a key-value pair in `node`.
820    /// Unsafe because the caller must ensure that `idx < node.len()`.
821    pub(super) unsafe fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
822        if true {
    if !(idx < node.len()) {
        ::core::panicking::panic("assertion failed: idx < node.len()")
    };
};debug_assert!(idx < node.len());
823
824        Handle { node, idx, _marker: PhantomData }
825    }
826
827    pub(super) fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
828        // ignore-tidy-undocumented-unsafe
829        unsafe { Handle::new_edge(self.node, self.idx) }
830    }
831
832    pub(super) fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
833        // ignore-tidy-undocumented-unsafe
834        unsafe { Handle::new_edge(self.node, self.idx + 1) }
835    }
836}
837
838impl<BorrowType, K, V, NodeType, HandleType> PartialEq
839    for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
840{
841    fn eq(&self, other: &Self) -> bool {
842        let Self { node, idx, _marker } = self;
843        node.eq(&other.node) && *idx == other.idx
844    }
845}
846
847impl<BorrowType, K, V, NodeType, HandleType>
848    Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
849{
850    /// Temporarily takes out another immutable handle on the same location.
851    pub(super) fn reborrow(
852        &self,
853    ) -> Handle<NodeRef<marker::Immut<'_>, K, V, NodeType>, HandleType> {
854        // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
855        Handle { node: self.node.reborrow(), idx: self.idx, _marker: PhantomData }
856    }
857}
858
859impl<'a, K, V, NodeType, HandleType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
860    /// Temporarily takes out another mutable handle on the same location. Beware, as
861    /// this method is very dangerous, doubly so since it might not immediately appear
862    /// dangerous.
863    ///
864    /// For details, see `NodeRef::reborrow_mut`.
865    pub(super) unsafe fn reborrow_mut(
866        &mut self,
867    ) -> Handle<NodeRef<marker::Mut<'_>, K, V, NodeType>, HandleType> {
868        // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
869        // ignore-tidy-undocumented-unsafe
870        Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData }
871    }
872
873    /// Returns a dormant copy of this handle which can be reawakened later.
874    ///
875    /// See `DormantMutRef` for more details.
876    pub(super) fn dormant(
877        &self,
878    ) -> Handle<NodeRef<marker::DormantMut, K, V, NodeType>, HandleType> {
879        Handle { node: self.node.dormant(), idx: self.idx, _marker: PhantomData }
880    }
881}
882
883impl<K, V, NodeType, HandleType> Handle<NodeRef<marker::DormantMut, K, V, NodeType>, HandleType> {
884    /// Revert to the unique borrow initially captured.
885    ///
886    /// # Safety
887    ///
888    /// The reborrow must have ended, i.e., the reference returned by `new` and
889    /// all pointers and references derived from it, must not be used anymore.
890    pub(super) unsafe fn awaken<'a>(
891        self,
892    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
893        // ignore-tidy-undocumented-unsafe
894        Handle { node: unsafe { self.node.awaken() }, idx: self.idx, _marker: PhantomData }
895    }
896}
897
898impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
899    /// Creates a new handle to an edge in `node`.
900    /// Unsafe because the caller must ensure that `idx <= node.len()`.
901    pub(super) unsafe fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
902        if true {
    if !(idx <= node.len()) {
        ::core::panicking::panic("assertion failed: idx <= node.len()")
    };
};debug_assert!(idx <= node.len());
903
904        Handle { node, idx, _marker: PhantomData }
905    }
906
907    pub(super) fn left_kv(
908        self,
909    ) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
910        if self.idx > 0 {
911            // ignore-tidy-undocumented-unsafe
912            Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) })
913        } else {
914            Err(self)
915        }
916    }
917
918    pub(super) fn right_kv(
919        self,
920    ) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
921        if self.idx < self.node.len() {
922            // ignore-tidy-undocumented-unsafe
923            Ok(unsafe { Handle::new_kv(self.node, self.idx) })
924        } else {
925            Err(self)
926        }
927    }
928}
929
930pub(super) enum LeftOrRight<T> {
931    Left(T),
932    Right(T),
933}
934
935/// Given an edge index where we want to insert into a node filled to capacity,
936/// computes a sensible KV index of a split point and where to perform the insertion.
937/// The goal of the split point is for its key and value to end up in a parent node;
938/// the keys, values and edges to the left of the split point become the left child;
939/// the keys, values and edges to the right of the split point become the right child.
940fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight<usize>) {
941    if true {
    if !(edge_idx <= CAPACITY) {
        ::core::panicking::panic("assertion failed: edge_idx <= CAPACITY")
    };
};debug_assert!(edge_idx <= CAPACITY);
942    // Rust issue #74834 tries to explain these symmetric rules.
943    match edge_idx {
944        0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)),
945        EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)),
946        EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)),
947        _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))),
948    }
949}
950
951impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
952    /// Inserts a new key-value pair between the key-value pairs to the right and left of
953    /// this edge. This method assumes that there is enough space in the node for the new
954    /// pair to fit.
955    unsafe fn insert_fit(
956        mut self,
957        key: K,
958        val: V,
959    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
960        if true {
    if !(self.node.len() < CAPACITY) {
        ::core::panicking::panic("assertion failed: self.node.len() < CAPACITY")
    };
};debug_assert!(self.node.len() < CAPACITY);
961        let new_len = self.node.len() + 1;
962
963        // ignore-tidy-undocumented-unsafe
964        unsafe {
965            slice_insert(self.node.key_area_mut(..new_len), self.idx, key);
966            slice_insert(self.node.val_area_mut(..new_len), self.idx, val);
967            *self.node.len_mut() = new_len as u16;
968
969            Handle::new_kv(self.node, self.idx)
970        }
971    }
972}
973
974impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
975    /// Inserts a new key-value pair between the key-value pairs to the right and left of
976    /// this edge. This method splits the node if there isn't enough room.
977    ///
978    /// Returns a dormant handle to the inserted node which can be reawakened
979    /// once splitting is complete.
980    fn insert<A: AllocatorClone>(
981        self,
982        key: K,
983        val: V,
984        alloc: A,
985    ) -> (
986        Option<SplitResult<'a, K, V, marker::Leaf>>,
987        Handle<NodeRef<marker::DormantMut, K, V, marker::Leaf>, marker::KV>,
988    ) {
989        if self.node.len() < CAPACITY {
990            // SAFETY: There is enough space in the node for insertion.
991            let handle = unsafe { self.insert_fit(key, val) };
992            (None, handle.dormant())
993        } else {
994            let (middle_kv_idx, insertion) = splitpoint(self.idx);
995            // ignore-tidy-undocumented-unsafe
996            let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
997            let mut result = middle.split(alloc);
998            let insertion_edge = match insertion {
999                // ignore-tidy-undocumented-unsafe
1000                LeftOrRight::Left(insert_idx) => unsafe {
1001                    Handle::new_edge(result.left.reborrow_mut(), insert_idx)
1002                },
1003                // ignore-tidy-undocumented-unsafe
1004                LeftOrRight::Right(insert_idx) => unsafe {
1005                    Handle::new_edge(result.right.borrow_mut(), insert_idx)
1006                },
1007            };
1008            // SAFETY: We just split the node, so there is enough space for
1009            // insertion.
1010            let handle = unsafe { insertion_edge.insert_fit(key, val).dormant() };
1011            (Some(result), handle)
1012        }
1013    }
1014}
1015
1016impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1017    /// Fixes the parent pointer and index in the child node that this edge
1018    /// links to. This is useful when the ordering of edges has been changed,
1019    fn correct_parent_link(self) {
1020        // Create backpointer without invalidating other references to the node.
1021        // ignore-tidy-undocumented-unsafe
1022        let ptr = unsafe { NonNull::new_unchecked(NodeRef::as_internal_ptr(&self.node)) };
1023        let idx = self.idx;
1024        let mut child = self.descend();
1025        child.set_parent_link(ptr, idx);
1026    }
1027}
1028
1029impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1030    /// Inserts a new key-value pair and an edge that will go to the right of that new pair
1031    /// between this edge and the key-value pair to the right of this edge. This method assumes
1032    /// that there is enough space in the node for the new pair to fit.
1033    fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
1034        if true {
    if !(self.node.len() < CAPACITY) {
        ::core::panicking::panic("assertion failed: self.node.len() < CAPACITY")
    };
};debug_assert!(self.node.len() < CAPACITY);
1035        if true {
    if !(edge.height == self.node.height - 1) {
        ::core::panicking::panic("assertion failed: edge.height == self.node.height - 1")
    };
};debug_assert!(edge.height == self.node.height - 1);
1036        let new_len = self.node.len() + 1;
1037
1038        // ignore-tidy-undocumented-unsafe
1039        unsafe {
1040            slice_insert(self.node.key_area_mut(..new_len), self.idx, key);
1041            slice_insert(self.node.val_area_mut(..new_len), self.idx, val);
1042            slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node);
1043            *self.node.len_mut() = new_len as u16;
1044
1045            self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1);
1046        }
1047    }
1048
1049    /// Inserts a new key-value pair and an edge that will go to the right of that new pair
1050    /// between this edge and the key-value pair to the right of this edge. This method splits
1051    /// the node if there isn't enough room.
1052    fn insert<A: AllocatorClone>(
1053        mut self,
1054        key: K,
1055        val: V,
1056        edge: Root<K, V>,
1057        alloc: A,
1058    ) -> Option<SplitResult<'a, K, V, marker::Internal>> {
1059        if !(edge.height == self.node.height - 1) {
    ::core::panicking::panic("assertion failed: edge.height == self.node.height - 1")
};assert!(edge.height == self.node.height - 1);
1060
1061        if self.node.len() < CAPACITY {
1062            self.insert_fit(key, val, edge);
1063            None
1064        } else {
1065            let (middle_kv_idx, insertion) = splitpoint(self.idx);
1066            // ignore-tidy-undocumented-unsafe
1067            let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
1068            let mut result = middle.split(alloc);
1069            let mut insertion_edge = match insertion {
1070                // ignore-tidy-undocumented-unsafe
1071                LeftOrRight::Left(insert_idx) => unsafe {
1072                    Handle::new_edge(result.left.reborrow_mut(), insert_idx)
1073                },
1074                // ignore-tidy-undocumented-unsafe
1075                LeftOrRight::Right(insert_idx) => unsafe {
1076                    Handle::new_edge(result.right.borrow_mut(), insert_idx)
1077                },
1078            };
1079            insertion_edge.insert_fit(key, val, edge);
1080            Some(result)
1081        }
1082    }
1083}
1084
1085impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
1086    /// Inserts a new key-value pair between the key-value pairs to the right and left of
1087    /// this edge. This method splits the node if there isn't enough room, and tries to
1088    /// insert the split off portion into the parent node recursively, until the root is reached.
1089    ///
1090    /// If the returned result is some `SplitResult`, the `left` field will be the root node.
1091    /// The returned pointer points to the inserted value, which in the case of `SplitResult`
1092    /// is in the `left` or `right` tree.
1093    pub(super) fn insert_recursing<A: AllocatorClone>(
1094        self,
1095        key: K,
1096        value: V,
1097        alloc: A,
1098        split_root: impl FnOnce(SplitResult<'a, K, V, marker::LeafOrInternal>),
1099    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1100        let (mut split, handle) = match self.insert(key, value, alloc.clone()) {
1101            // SAFETY: we have finished splitting and can now re-awaken the
1102            // handle to the inserted element.
1103            (None, handle) => return unsafe { handle.awaken() },
1104            (Some(split), handle) => (split.forget_node_type(), handle),
1105        };
1106
1107        loop {
1108            split = match split.left.ascend() {
1109                Ok(parent) => {
1110                    match parent.insert(split.kv.0, split.kv.1, split.right, alloc.clone()) {
1111                        // SAFETY: we have finished splitting and can now re-awaken the
1112                        // handle to the inserted element.
1113                        None => return unsafe { handle.awaken() },
1114                        Some(split) => split.forget_node_type(),
1115                    }
1116                }
1117                Err(root) => {
1118                    split_root(SplitResult { left: root, ..split });
1119                    // SAFETY: we have finished splitting and can now re-awaken the
1120                    // handle to the inserted element.
1121                    return unsafe { handle.awaken() };
1122                }
1123            };
1124        }
1125    }
1126}
1127
1128impl<BorrowType: marker::BorrowType, K, V>
1129    Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>
1130{
1131    /// Finds the node pointed to by this edge.
1132    ///
1133    /// The method name assumes you picture trees with the root node on top.
1134    ///
1135    /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
1136    /// both, upon success, do nothing.
1137    pub(super) fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1138        const {
1139            if !BorrowType::TRAVERSAL_PERMIT {
    ::core::panicking::panic("assertion failed: BorrowType::TRAVERSAL_PERMIT")
};assert!(BorrowType::TRAVERSAL_PERMIT);
1140        }
1141
1142        // We need to use raw pointers to nodes because, if BorrowType is
1143        // marker::ValMut, there might be outstanding mutable references to
1144        // values that we must not invalidate. There's no worry accessing the
1145        // height field because that value is copied. Beware that, once the
1146        // node pointer is dereferenced, we access the edges array with a
1147        // reference (Rust issue #73987) and invalidate any other references
1148        // to or inside the array, should any be around.
1149        let parent_ptr = NodeRef::as_internal_ptr(&self.node);
1150        // ignore-tidy-undocumented-unsafe
1151        let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() };
1152        NodeRef { node, height: self.node.height - 1, _marker: PhantomData }
1153    }
1154}
1155
1156impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
1157    pub(super) fn into_kv(self) -> (&'a K, &'a V) {
1158        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1159        let leaf = self.node.into_leaf();
1160        // ignore-tidy-undocumented-unsafe
1161        let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() };
1162        // ignore-tidy-undocumented-unsafe
1163        let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() };
1164        (k, v)
1165    }
1166}
1167
1168impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1169    pub(super) fn key_mut(&mut self) -> &mut K {
1170        // ignore-tidy-undocumented-unsafe
1171        unsafe { self.node.key_area_mut(self.idx).assume_init_mut() }
1172    }
1173
1174    pub(super) fn into_val_mut(self) -> &'a mut V {
1175        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1176        let leaf = self.node.into_leaf_mut();
1177        // ignore-tidy-undocumented-unsafe
1178        unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() }
1179    }
1180
1181    pub(super) fn into_kv_mut(self) -> (&'a mut K, &'a mut V) {
1182        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1183        let leaf = self.node.into_leaf_mut();
1184        // ignore-tidy-undocumented-unsafe
1185        let k = unsafe { leaf.keys.get_unchecked_mut(self.idx).assume_init_mut() };
1186        // ignore-tidy-undocumented-unsafe
1187        let v = unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() };
1188        (k, v)
1189    }
1190}
1191
1192impl<'a, K, V, NodeType> Handle<NodeRef<marker::ValMut<'a>, K, V, NodeType>, marker::KV> {
1193    pub(super) fn into_kv_valmut(self) -> (&'a K, &'a mut V) {
1194        // ignore-tidy-undocumented-unsafe
1195        unsafe { self.node.into_key_val_mut_at(self.idx) }
1196    }
1197}
1198
1199impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1200    pub(super) fn kv_mut(&mut self) -> (&mut K, &mut V) {
1201        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1202        // We cannot call separate key and value methods, because calling the second one
1203        // invalidates the reference returned by the first.
1204        // ignore-tidy-undocumented-unsafe
1205        unsafe {
1206            let leaf = self.node.as_leaf_mut();
1207            let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut();
1208            let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut();
1209            (key, val)
1210        }
1211    }
1212
1213    /// Replaces the key and value that the KV handle refers to.
1214    pub(super) fn replace_kv(&mut self, k: K, v: V) -> (K, V) {
1215        let (key, val) = self.kv_mut();
1216        (mem::replace(key, k), mem::replace(val, v))
1217    }
1218}
1219
1220impl<K, V, NodeType> Handle<NodeRef<marker::Dying, K, V, NodeType>, marker::KV> {
1221    /// Extracts the key and value that the KV handle refers to.
1222    /// # Safety
1223    /// The node that the handle refers to must not yet have been deallocated.
1224    pub(super) unsafe fn into_key_val(mut self) -> (K, V) {
1225        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1226        let leaf = self.node.as_leaf_dying();
1227        // ignore-tidy-undocumented-unsafe
1228        unsafe {
1229            let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_read();
1230            let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_read();
1231            (key, val)
1232        }
1233    }
1234
1235    /// Drops the key and value that the KV handle refers to.
1236    /// # Safety
1237    /// The node that the handle refers to must not yet have been deallocated.
1238    #[inline]
1239    pub(super) unsafe fn drop_key_val(mut self) {
1240        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1241        let leaf = self.node.as_leaf_dying();
1242        // ignore-tidy-undocumented-unsafe
1243        unsafe {
1244            let key = leaf.keys.get_unchecked_mut(self.idx);
1245            let val = leaf.vals.get_unchecked_mut(self.idx);
1246            // Run the destructor of the value even if the destructor of the key panics.
1247            let _guard = DropGuard::new(val, |val| val.assume_init_drop());
1248            key.assume_init_drop();
1249            // dropping the guard will drop the value
1250        }
1251    }
1252}
1253
1254impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1255    /// Helps implementations of `split` for a particular `NodeType`,
1256    /// by taking care of leaf data.
1257    fn split_leaf_data(&mut self, new_node: &mut LeafNode<K, V>) -> (K, V) {
1258        if true {
    if !(self.idx < self.node.len()) {
        ::core::panicking::panic("assertion failed: self.idx < self.node.len()")
    };
};debug_assert!(self.idx < self.node.len());
1259        let old_len = self.node.len();
1260        let new_len = old_len - self.idx - 1;
1261        new_node.len = new_len as u16;
1262        // ignore-tidy-undocumented-unsafe
1263        unsafe {
1264            let k = self.node.key_area_mut(self.idx).assume_init_read();
1265            let v = self.node.val_area_mut(self.idx).assume_init_read();
1266
1267            move_to_slice(
1268                self.node.key_area_mut(self.idx + 1..old_len),
1269                &mut new_node.keys[..new_len],
1270            );
1271            move_to_slice(
1272                self.node.val_area_mut(self.idx + 1..old_len),
1273                &mut new_node.vals[..new_len],
1274            );
1275
1276            *self.node.len_mut() = self.idx as u16;
1277            (k, v)
1278        }
1279    }
1280}
1281
1282impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1283    /// Splits the underlying node into three parts:
1284    ///
1285    /// - The node is truncated to only contain the key-value pairs to the left of
1286    ///   this handle.
1287    /// - The key and value pointed to by this handle are extracted.
1288    /// - All the key-value pairs to the right of this handle are put into a newly
1289    ///   allocated node.
1290    pub(super) fn split<A: AllocatorClone>(
1291        mut self,
1292        alloc: A,
1293    ) -> SplitResult<'a, K, V, marker::Leaf> {
1294        let mut new_node = LeafNode::new(alloc);
1295
1296        let kv = self.split_leaf_data(&mut new_node);
1297
1298        let right = NodeRef::from_new_leaf(new_node);
1299        SplitResult { left: self.node, kv, right }
1300    }
1301
1302    /// Removes the key-value pair pointed to by this handle and returns it, along with the edge
1303    /// that the key-value pair collapsed into.
1304    pub(super) fn remove(
1305        mut self,
1306    ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
1307        let old_len = self.node.len();
1308        // ignore-tidy-undocumented-unsafe
1309        unsafe {
1310            let k = slice_remove(self.node.key_area_mut(..old_len), self.idx);
1311            let v = slice_remove(self.node.val_area_mut(..old_len), self.idx);
1312            *self.node.len_mut() = (old_len - 1) as u16;
1313            ((k, v), self.left_edge())
1314        }
1315    }
1316}
1317
1318impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1319    /// Splits the underlying node into three parts:
1320    ///
1321    /// - The node is truncated to only contain the edges and key-value pairs to the
1322    ///   left of this handle.
1323    /// - The key and value pointed to by this handle are extracted.
1324    /// - All the edges and key-value pairs to the right of this handle are put into
1325    ///   a newly allocated node.
1326    pub(super) fn split<A: AllocatorClone>(
1327        mut self,
1328        alloc: A,
1329    ) -> SplitResult<'a, K, V, marker::Internal> {
1330        let old_len = self.node.len();
1331        // ignore-tidy-undocumented-unsafe
1332        unsafe {
1333            let mut new_node = InternalNode::new(alloc);
1334            let kv = self.split_leaf_data(&mut new_node.data);
1335            let new_len = usize::from(new_node.data.len);
1336            move_to_slice(
1337                self.node.edge_area_mut(self.idx + 1..old_len + 1),
1338                &mut new_node.edges[..new_len + 1],
1339            );
1340
1341            // SAFETY: self is `marker::Internal`, so `self.node.height` is positive
1342            let height = NonZero::new_unchecked(self.node.height);
1343            let right = NodeRef::from_new_internal(new_node, height);
1344
1345            SplitResult { left: self.node, kv, right }
1346        }
1347    }
1348}
1349
1350/// Represents a session for evaluating and performing a balancing operation
1351/// around an internal key-value pair.
1352pub(super) struct BalancingContext<'a, K, V> {
1353    parent: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV>,
1354    left_child: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1355    right_child: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1356}
1357
1358impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1359    pub(super) fn consider_for_balancing(self) -> BalancingContext<'a, K, V> {
1360        // ignore-tidy-undocumented-unsafe
1361        let self1 = unsafe { ptr::read(&self) };
1362        // ignore-tidy-undocumented-unsafe
1363        let self2 = unsafe { ptr::read(&self) };
1364        BalancingContext {
1365            parent: self,
1366            left_child: self1.left_edge().descend(),
1367            right_child: self2.right_edge().descend(),
1368        }
1369    }
1370}
1371
1372impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1373    /// Chooses a balancing context involving the node as a child, thus between
1374    /// the KV immediately to the left or to the right in the parent node.
1375    /// Returns an `Err` if there is no parent.
1376    /// Panics if the parent is empty.
1377    ///
1378    /// Prefers the left side, to be optimal if the given node is somehow
1379    /// underfull, meaning here only that it has fewer elements than its left
1380    /// sibling and than its right sibling, if they exist. In that case,
1381    /// merging with the left sibling is faster, since we only need to move
1382    /// the node's N elements, instead of shifting them to the right and moving
1383    /// more than N elements in front. Stealing from the left sibling is also
1384    /// typically faster, since we only need to shift the node's N elements to
1385    /// the right, instead of shifting at least N of the sibling's elements to
1386    /// the left.
1387    pub(super) fn choose_parent_kv(self) -> Result<LeftOrRight<BalancingContext<'a, K, V>>, Self> {
1388        // ignore-tidy-undocumented-unsafe
1389        match unsafe { ptr::read(&self) }.ascend() {
1390            Ok(parent_edge) => match parent_edge.left_kv() {
1391                Ok(left_parent_kv) => Ok(LeftOrRight::Left(BalancingContext {
1392                    // ignore-tidy-undocumented-unsafe
1393                    parent: unsafe { ptr::read(&left_parent_kv) },
1394                    left_child: left_parent_kv.left_edge().descend(),
1395                    right_child: self,
1396                })),
1397                Err(parent_edge) => match parent_edge.right_kv() {
1398                    Ok(right_parent_kv) => Ok(LeftOrRight::Right(BalancingContext {
1399                        // ignore-tidy-undocumented-unsafe
1400                        parent: unsafe { ptr::read(&right_parent_kv) },
1401                        left_child: self,
1402                        right_child: right_parent_kv.right_edge().descend(),
1403                    })),
1404                    Err(_) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("empty internal node")));
}unreachable!("empty internal node"),
1405                },
1406            },
1407            Err(root) => Err(root),
1408        }
1409    }
1410}
1411
1412impl<'a, K, V> BalancingContext<'a, K, V> {
1413    pub(super) fn left_child_len(&self) -> usize {
1414        self.left_child.len()
1415    }
1416
1417    pub(super) fn right_child_len(&self) -> usize {
1418        self.right_child.len()
1419    }
1420
1421    pub(super) fn into_left_child(self) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1422        self.left_child
1423    }
1424
1425    pub(super) fn into_right_child(self) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1426        self.right_child
1427    }
1428
1429    /// Returns whether merging is possible, i.e., whether there is enough room
1430    /// in a node to combine the central KV with both adjacent child nodes.
1431    pub(super) fn can_merge(&self) -> bool {
1432        self.left_child.len() + 1 + self.right_child.len() <= CAPACITY
1433    }
1434}
1435
1436impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> {
1437    /// Performs a merge and lets a closure decide what to return.
1438    fn do_merge<
1439        F: FnOnce(
1440            NodeRef<marker::Mut<'a>, K, V, marker::Internal>,
1441            NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1442        ) -> R,
1443        R,
1444        A: Allocator,
1445    >(
1446        self,
1447        result: F,
1448        alloc: A,
1449    ) -> R {
1450        let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent;
1451        let old_parent_len = parent_node.len();
1452        let mut left_node = self.left_child;
1453        let old_left_len = left_node.len();
1454        let mut right_node = self.right_child;
1455        let right_len = right_node.len();
1456        let new_left_len = old_left_len + 1 + right_len;
1457
1458        if !(new_left_len <= CAPACITY) {
    ::core::panicking::panic("assertion failed: new_left_len <= CAPACITY")
};assert!(new_left_len <= CAPACITY);
1459
1460        // ignore-tidy-undocumented-unsafe
1461        unsafe {
1462            *left_node.len_mut() = new_left_len as u16;
1463
1464            let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx);
1465            left_node.key_area_mut(old_left_len).write(parent_key);
1466            move_to_slice(
1467                right_node.key_area_mut(..right_len),
1468                left_node.key_area_mut(old_left_len + 1..new_left_len),
1469            );
1470
1471            let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx);
1472            left_node.val_area_mut(old_left_len).write(parent_val);
1473            move_to_slice(
1474                right_node.val_area_mut(..right_len),
1475                left_node.val_area_mut(old_left_len + 1..new_left_len),
1476            );
1477
1478            slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1);
1479            parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len);
1480            *parent_node.len_mut() -= 1;
1481
1482            if parent_node.height > 1 {
1483                // SAFETY: the height of the nodes being merged is one below the height
1484                // of the node of this edge, thus above zero, so they are internal.
1485                let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked();
1486                let mut right_node = right_node.cast_to_internal_unchecked();
1487                move_to_slice(
1488                    right_node.edge_area_mut(..right_len + 1),
1489                    left_node.edge_area_mut(old_left_len + 1..new_left_len + 1),
1490                );
1491
1492                left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1);
1493
1494                alloc.deallocate(right_node.node.cast(), Layout::new::<InternalNode<K, V>>());
1495            } else {
1496                alloc.deallocate(right_node.node.cast(), Layout::new::<LeafNode<K, V>>());
1497            }
1498        }
1499        result(parent_node, left_node)
1500    }
1501
1502    /// Merges the parent's key-value pair and both adjacent child nodes into
1503    /// the left child node and returns the shrunk parent node.
1504    ///
1505    /// Panics unless we `.can_merge()`.
1506    pub(super) fn merge_tracking_parent<A: AllocatorClone>(
1507        self,
1508        alloc: A,
1509    ) -> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
1510        self.do_merge(|parent, _child| parent, alloc)
1511    }
1512
1513    /// Merges the parent's key-value pair and both adjacent child nodes into
1514    /// the left child node and returns that child node.
1515    ///
1516    /// Panics unless we `.can_merge()`.
1517    pub(super) fn merge_tracking_child<A: AllocatorClone>(
1518        self,
1519        alloc: A,
1520    ) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1521        self.do_merge(|_parent, child| child, alloc)
1522    }
1523
1524    /// Merges the parent's key-value pair and both adjacent child nodes into
1525    /// the left child node and returns the edge handle in that child node
1526    /// where the tracked child edge ended up,
1527    ///
1528    /// Panics unless we `.can_merge()`.
1529    pub(super) fn merge_tracking_child_edge<A: AllocatorClone>(
1530        self,
1531        track_edge_idx: LeftOrRight<usize>,
1532        alloc: A,
1533    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1534        let old_left_len = self.left_child.len();
1535        let right_len = self.right_child.len();
1536        if !match track_edge_idx {
            LeftOrRight::Left(idx) => idx <= old_left_len,
            LeftOrRight::Right(idx) => idx <= right_len,
        } {
    ::core::panicking::panic("assertion failed: match track_edge_idx {\n    LeftOrRight::Left(idx) => idx <= old_left_len,\n    LeftOrRight::Right(idx) => idx <= right_len,\n}")
};assert!(match track_edge_idx {
1537            LeftOrRight::Left(idx) => idx <= old_left_len,
1538            LeftOrRight::Right(idx) => idx <= right_len,
1539        });
1540        let child = self.merge_tracking_child(alloc);
1541        let new_idx = match track_edge_idx {
1542            LeftOrRight::Left(idx) => idx,
1543            LeftOrRight::Right(idx) => old_left_len + 1 + idx,
1544        };
1545        // ignore-tidy-undocumented-unsafe
1546        unsafe { Handle::new_edge(child, new_idx) }
1547    }
1548
1549    /// Removes a key-value pair from the left child and places it in the key-value storage
1550    /// of the parent, while pushing the old parent key-value pair into the right child.
1551    /// Returns a handle to the edge in the right child corresponding to where the original
1552    /// edge specified by `track_right_edge_idx` ended up.
1553    pub(super) fn steal_left(
1554        mut self,
1555        track_right_edge_idx: usize,
1556    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1557        self.bulk_steal_left(1);
1558        // ignore-tidy-undocumented-unsafe
1559        unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) }
1560    }
1561
1562    /// Removes a key-value pair from the right child and places it in the key-value storage
1563    /// of the parent, while pushing the old parent key-value pair onto the left child.
1564    /// Returns a handle to the edge in the left child specified by `track_left_edge_idx`,
1565    /// which didn't move.
1566    pub(super) fn steal_right(
1567        mut self,
1568        track_left_edge_idx: usize,
1569    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1570        self.bulk_steal_right(1);
1571        // ignore-tidy-undocumented-unsafe
1572        unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) }
1573    }
1574
1575    /// This does stealing similar to `steal_left` but steals multiple elements at once.
1576    pub(super) fn bulk_steal_left(&mut self, count: usize) {
1577        if !(count > 0) { ::core::panicking::panic("assertion failed: count > 0") };assert!(count > 0);
1578        // ignore-tidy-undocumented-unsafe
1579        unsafe {
1580            let left_node = &mut self.left_child;
1581            let old_left_len = left_node.len();
1582            let right_node = &mut self.right_child;
1583            let old_right_len = right_node.len();
1584
1585            // Make sure that we may steal safely.
1586            if !(old_right_len + count <= CAPACITY) {
    ::core::panicking::panic("assertion failed: old_right_len + count <= CAPACITY")
};assert!(old_right_len + count <= CAPACITY);
1587            if !(old_left_len >= count) {
    ::core::panicking::panic("assertion failed: old_left_len >= count")
};assert!(old_left_len >= count);
1588
1589            let new_left_len = old_left_len - count;
1590            let new_right_len = old_right_len + count;
1591            *left_node.len_mut() = new_left_len as u16;
1592            *right_node.len_mut() = new_right_len as u16;
1593
1594            // Move leaf data.
1595            {
1596                // Make room for stolen elements in the right child.
1597                slice_shr(right_node.key_area_mut(..new_right_len), count);
1598                slice_shr(right_node.val_area_mut(..new_right_len), count);
1599
1600                // Move elements from the left child to the right one.
1601                move_to_slice(
1602                    left_node.key_area_mut(new_left_len + 1..old_left_len),
1603                    right_node.key_area_mut(..count - 1),
1604                );
1605                move_to_slice(
1606                    left_node.val_area_mut(new_left_len + 1..old_left_len),
1607                    right_node.val_area_mut(..count - 1),
1608                );
1609
1610                // Move the leftmost stolen pair to the parent.
1611                let k = left_node.key_area_mut(new_left_len).assume_init_read();
1612                let v = left_node.val_area_mut(new_left_len).assume_init_read();
1613                let (k, v) = self.parent.replace_kv(k, v);
1614
1615                // Move parent's key-value pair to the right child.
1616                right_node.key_area_mut(count - 1).write(k);
1617                right_node.val_area_mut(count - 1).write(v);
1618            }
1619
1620            match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) {
1621                (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1622                    // Make room for stolen edges.
1623                    slice_shr(right.edge_area_mut(..new_right_len + 1), count);
1624
1625                    // Steal edges.
1626                    move_to_slice(
1627                        left.edge_area_mut(new_left_len + 1..old_left_len + 1),
1628                        right.edge_area_mut(..count),
1629                    );
1630
1631                    right.correct_childrens_parent_links(0..new_right_len + 1);
1632                }
1633                (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1634                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1635            }
1636        }
1637    }
1638
1639    /// The symmetric clone of `bulk_steal_left`.
1640    pub(super) fn bulk_steal_right(&mut self, count: usize) {
1641        if !(count > 0) { ::core::panicking::panic("assertion failed: count > 0") };assert!(count > 0);
1642        // ignore-tidy-undocumented-unsafe
1643        unsafe {
1644            let left_node = &mut self.left_child;
1645            let old_left_len = left_node.len();
1646            let right_node = &mut self.right_child;
1647            let old_right_len = right_node.len();
1648
1649            // Make sure that we may steal safely.
1650            if !(old_left_len + count <= CAPACITY) {
    ::core::panicking::panic("assertion failed: old_left_len + count <= CAPACITY")
};assert!(old_left_len + count <= CAPACITY);
1651            if !(old_right_len >= count) {
    ::core::panicking::panic("assertion failed: old_right_len >= count")
};assert!(old_right_len >= count);
1652
1653            let new_left_len = old_left_len + count;
1654            let new_right_len = old_right_len - count;
1655            *left_node.len_mut() = new_left_len as u16;
1656            *right_node.len_mut() = new_right_len as u16;
1657
1658            // Move leaf data.
1659            {
1660                // Move the rightmost stolen pair to the parent.
1661                let k = right_node.key_area_mut(count - 1).assume_init_read();
1662                let v = right_node.val_area_mut(count - 1).assume_init_read();
1663                let (k, v) = self.parent.replace_kv(k, v);
1664
1665                // Move parent's key-value pair to the left child.
1666                left_node.key_area_mut(old_left_len).write(k);
1667                left_node.val_area_mut(old_left_len).write(v);
1668
1669                // Move elements from the right child to the left one.
1670                move_to_slice(
1671                    right_node.key_area_mut(..count - 1),
1672                    left_node.key_area_mut(old_left_len + 1..new_left_len),
1673                );
1674                move_to_slice(
1675                    right_node.val_area_mut(..count - 1),
1676                    left_node.val_area_mut(old_left_len + 1..new_left_len),
1677                );
1678
1679                // Fill gap where stolen elements used to be.
1680                slice_shl(right_node.key_area_mut(..old_right_len), count);
1681                slice_shl(right_node.val_area_mut(..old_right_len), count);
1682            }
1683
1684            match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) {
1685                (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1686                    // Steal edges.
1687                    move_to_slice(
1688                        right.edge_area_mut(..count),
1689                        left.edge_area_mut(old_left_len + 1..new_left_len + 1),
1690                    );
1691
1692                    // Fill gap where stolen edges used to be.
1693                    slice_shl(right.edge_area_mut(..old_right_len + 1), count);
1694
1695                    left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1);
1696                    right.correct_childrens_parent_links(0..new_right_len + 1);
1697                }
1698                (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1699                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1700            }
1701        }
1702    }
1703}
1704
1705impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1706    pub(super) fn forget_node_type(
1707        self,
1708    ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1709        // ignore-tidy-undocumented-unsafe
1710        unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1711    }
1712}
1713
1714impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1715    pub(super) fn forget_node_type(
1716        self,
1717    ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1718        // ignore-tidy-undocumented-unsafe
1719        unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1720    }
1721}
1722
1723impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::KV> {
1724    pub(super) fn forget_node_type(
1725        self,
1726    ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1727        // ignore-tidy-undocumented-unsafe
1728        unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1729    }
1730}
1731
1732impl<BorrowType, K, V, Type> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, Type> {
1733    /// Checks whether the underlying node is an `Internal` node or a `Leaf` node.
1734    pub(super) fn force(
1735        self,
1736    ) -> ForceResult<
1737        Handle<NodeRef<BorrowType, K, V, marker::Leaf>, Type>,
1738        Handle<NodeRef<BorrowType, K, V, marker::Internal>, Type>,
1739    > {
1740        match self.node.force() {
1741            ForceResult::Leaf(node) => {
1742                ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData })
1743            }
1744            ForceResult::Internal(node) => {
1745                ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData })
1746            }
1747        }
1748    }
1749}
1750
1751impl<'a, K, V, Type> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, Type> {
1752    /// Unsafely asserts to the compiler the static information that the handle's node is a `Leaf`.
1753    pub(super) unsafe fn cast_to_leaf_unchecked(
1754        self,
1755    ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, Type> {
1756        // ignore-tidy-undocumented-unsafe
1757        let node = unsafe { self.node.cast_to_leaf_unchecked() };
1758        Handle { node, idx: self.idx, _marker: PhantomData }
1759    }
1760}
1761
1762impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1763    /// Move the suffix after `self` from one node to another one. `right` must be empty.
1764    /// The first edge of `right` remains unchanged.
1765    pub(super) fn move_suffix(
1766        &mut self,
1767        right: &mut NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1768    ) {
1769        // ignore-tidy-undocumented-unsafe
1770        unsafe {
1771            let new_left_len = self.idx;
1772            let mut left_node = self.reborrow_mut().into_node();
1773            let old_left_len = left_node.len();
1774
1775            let new_right_len = old_left_len - new_left_len;
1776            let mut right_node = right.reborrow_mut();
1777
1778            if !(right_node.len() == 0) {
    ::core::panicking::panic("assertion failed: right_node.len() == 0")
};assert!(right_node.len() == 0);
1779            if !(left_node.height == right_node.height) {
    ::core::panicking::panic("assertion failed: left_node.height == right_node.height")
};assert!(left_node.height == right_node.height);
1780
1781            if new_right_len > 0 {
1782                *left_node.len_mut() = new_left_len as u16;
1783                *right_node.len_mut() = new_right_len as u16;
1784
1785                move_to_slice(
1786                    left_node.key_area_mut(new_left_len..old_left_len),
1787                    right_node.key_area_mut(..new_right_len),
1788                );
1789                move_to_slice(
1790                    left_node.val_area_mut(new_left_len..old_left_len),
1791                    right_node.val_area_mut(..new_right_len),
1792                );
1793                match (left_node.force(), right_node.force()) {
1794                    (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1795                        move_to_slice(
1796                            left.edge_area_mut(new_left_len + 1..old_left_len + 1),
1797                            right.edge_area_mut(1..new_right_len + 1),
1798                        );
1799                        right.correct_childrens_parent_links(1..new_right_len + 1);
1800                    }
1801                    (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1802                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1803                }
1804            }
1805        }
1806    }
1807}
1808
1809pub(super) enum ForceResult<Leaf, Internal> {
1810    Leaf(Leaf),
1811    Internal(Internal),
1812}
1813
1814/// Result of insertion, when a node needed to expand beyond its capacity.
1815pub(super) struct SplitResult<'a, K, V, NodeType> {
1816    // Altered node in existing tree with elements and edges that belong to the left of `kv`.
1817    pub left: NodeRef<marker::Mut<'a>, K, V, NodeType>,
1818    // Some key and value that existed before and were split off, to be inserted elsewhere.
1819    pub kv: (K, V),
1820    // Owned, unattached, new node with elements and edges that belong to the right of `kv`.
1821    pub right: NodeRef<marker::Owned, K, V, NodeType>,
1822}
1823
1824impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> {
1825    pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> {
1826        SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() }
1827    }
1828}
1829
1830impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> {
1831    pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> {
1832        SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() }
1833    }
1834}
1835
1836pub(super) mod marker {
1837    use core::marker::PhantomData;
1838
1839    pub(crate) enum Leaf {}
1840    pub(crate) enum Internal {}
1841    pub(crate) enum LeafOrInternal {}
1842
1843    pub(crate) enum Owned {}
1844    pub(crate) enum Dying {}
1845    pub(crate) enum DormantMut {}
1846    pub(crate) struct Immut<'a>(PhantomData<&'a ()>);
1847    pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>);
1848    pub(crate) struct ValMut<'a>(PhantomData<&'a mut ()>);
1849
1850    pub(crate) trait BorrowType {
1851        /// If node references of this borrow type allow traversing to other
1852        /// nodes in the tree, this constant is set to `true`. It can be used
1853        /// for a compile-time assertion.
1854        const TRAVERSAL_PERMIT: bool = true;
1855    }
1856    impl BorrowType for Owned {
1857        /// Reject traversal, because it isn't needed. Instead traversal
1858        /// happens using the result of `borrow_mut`.
1859        /// By disabling traversal, and only creating new references to roots,
1860        /// we know that every reference of the `Owned` type is to a root node.
1861        const TRAVERSAL_PERMIT: bool = false;
1862    }
1863    impl BorrowType for Dying {}
1864    impl<'a> BorrowType for Immut<'a> {}
1865    impl<'a> BorrowType for Mut<'a> {}
1866    impl<'a> BorrowType for ValMut<'a> {}
1867    impl BorrowType for DormantMut {}
1868
1869    pub(crate) enum KV {}
1870    pub(crate) enum Edge {}
1871}
1872
1873/// Inserts a value into a slice of initialized elements followed by one uninitialized element.
1874///
1875/// # Safety
1876/// The slice has more than `idx` elements.
1877unsafe fn slice_insert<T>(slice: &mut [MaybeUninit<T>], idx: usize, val: T) {
1878    // ignore-tidy-undocumented-unsafe
1879    unsafe {
1880        let len = slice.len();
1881        if true {
    if !(len > idx) {
        ::core::panicking::panic("assertion failed: len > idx")
    };
};debug_assert!(len > idx);
1882        let slice_ptr = slice.as_mut_ptr();
1883        if len > idx + 1 {
1884            ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1);
1885        }
1886        (*slice_ptr.add(idx)).write(val);
1887    }
1888}
1889
1890/// Removes and returns a value from a slice of all initialized elements, leaving behind one
1891/// trailing uninitialized element.
1892///
1893/// # Safety
1894/// The slice has more than `idx` elements.
1895unsafe fn slice_remove<T>(slice: &mut [MaybeUninit<T>], idx: usize) -> T {
1896    // ignore-tidy-undocumented-unsafe
1897    unsafe {
1898        let len = slice.len();
1899        if true {
    if !(idx < len) {
        ::core::panicking::panic("assertion failed: idx < len")
    };
};debug_assert!(idx < len);
1900        let slice_ptr = slice.as_mut_ptr();
1901        let ret = (*slice_ptr.add(idx)).assume_init_read();
1902        ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1);
1903        ret
1904    }
1905}
1906
1907/// Shifts the elements in a slice `distance` positions to the left.
1908///
1909/// # Safety
1910/// The slice has at least `distance` elements.
1911unsafe fn slice_shl<T>(slice: &mut [MaybeUninit<T>], distance: usize) {
1912    // ignore-tidy-undocumented-unsafe
1913    unsafe {
1914        let slice_ptr = slice.as_mut_ptr();
1915        ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance);
1916    }
1917}
1918
1919/// Shifts the elements in a slice `distance` positions to the right.
1920///
1921/// # Safety
1922/// The slice has at least `distance` elements.
1923unsafe fn slice_shr<T>(slice: &mut [MaybeUninit<T>], distance: usize) {
1924    // ignore-tidy-undocumented-unsafe
1925    unsafe {
1926        let slice_ptr = slice.as_mut_ptr();
1927        ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance);
1928    }
1929}
1930
1931/// Moves all values from a slice of initialized elements to a slice
1932/// of uninitialized elements, leaving behind `src` as all uninitialized.
1933/// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`.
1934fn move_to_slice<T>(src: &mut [MaybeUninit<T>], dst: &mut [MaybeUninit<T>]) {
1935    if !(src.len() == dst.len()) {
    ::core::panicking::panic("assertion failed: src.len() == dst.len()")
};assert!(src.len() == dst.len());
1936    // ignore-tidy-undocumented-unsafe
1937    unsafe {
1938        ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());
1939    }
1940}
1941
1942#[cfg(test)]
1943mod tests;