]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/btree/node.rs
Add a comment why rustdoc loads crates from the sysroot
[rust.git] / library / alloc / src / 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 {
13 //         [Box<Node<K, V, height - 1>>; 2 * B]
14 //     } else { () },
15 //     parent: *const Node<K, V, height + 1>,
16 //     parent_idx: u16,
17 //     len: u16,
18 // }
19 // ```
20 //
21 // Since Rust doesn't actually have dependent types and polymorphic recursion,
22 // we make do with lots of unsafety.
23
24 // A major goal of this module is to avoid complexity by treating the tree as a generic (if
25 // weirdly shaped) container and avoiding dealing with most of the B-Tree invariants. As such,
26 // this module doesn't care whether the entries are sorted, which nodes can be underfull, or
27 // even what underfull means. However, we do rely on a few invariants:
28 //
29 // - Trees must have uniform depth/height. This means that every path down to a leaf from a
30 //   given node has exactly the same length.
31 // - A node of length `n` has `n` keys, `n` values, and (in an internal node) `n + 1` edges.
32 //   This implies that even an empty internal node has at least one edge.
33
34 use core::cmp::Ordering;
35 use core::marker::PhantomData;
36 use core::mem::{self, MaybeUninit};
37 use core::ptr::{self, NonNull, Unique};
38 use core::slice;
39
40 use crate::alloc::{AllocRef, Global, Layout};
41 use crate::boxed::Box;
42
43 const B: usize = 6;
44 pub const MIN_LEN: usize = B - 1;
45 pub const CAPACITY: usize = 2 * B - 1;
46 const KV_IDX_CENTER: usize = B - 1;
47 const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1;
48 const EDGE_IDX_RIGHT_OF_CENTER: usize = B;
49
50 /// The underlying representation of leaf nodes.
51 #[repr(C)]
52 struct LeafNode<K, V> {
53     /// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`.
54     /// This either points to an actual node or is null.
55     parent: *const InternalNode<K, V>,
56
57     /// This node's index into the parent node's `edges` array.
58     /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`.
59     /// This is only guaranteed to be initialized when `parent` is non-null.
60     parent_idx: MaybeUninit<u16>,
61
62     /// The number of keys and values this node stores.
63     ///
64     /// This next to `parent_idx` to encourage the compiler to join `len` and
65     /// `parent_idx` into the same 32-bit word, reducing space overhead.
66     len: u16,
67
68     /// The arrays storing the actual data of the node. Only the first `len` elements of each
69     /// array are initialized and valid.
70     keys: [MaybeUninit<K>; CAPACITY],
71     vals: [MaybeUninit<V>; CAPACITY],
72 }
73
74 impl<K, V> LeafNode<K, V> {
75     /// Creates a new `LeafNode`. Unsafe because all nodes should really be hidden behind
76     /// `BoxedNode`, preventing accidental dropping of uninitialized keys and values.
77     unsafe fn new() -> Self {
78         LeafNode {
79             // As a general policy, we leave fields uninitialized if they can be, as this should
80             // be both slightly faster and easier to track in Valgrind.
81             keys: [MaybeUninit::UNINIT; CAPACITY],
82             vals: [MaybeUninit::UNINIT; CAPACITY],
83             parent: ptr::null(),
84             parent_idx: MaybeUninit::uninit(),
85             len: 0,
86         }
87     }
88 }
89
90 /// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden
91 /// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an
92 /// `InternalNode` can be directly casted to a pointer to the underlying `LeafNode` portion of the
93 /// node, allowing code to act on leaf and internal nodes generically without having to even check
94 /// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`.
95 #[repr(C)]
96 struct InternalNode<K, V> {
97     data: LeafNode<K, V>,
98
99     /// The pointers to the children of this node. `len + 1` of these are considered
100     /// initialized and valid. Although during the process of `into_iter` or `drop`,
101     /// some pointers are dangling while others still need to be traversed.
102     edges: [MaybeUninit<BoxedNode<K, V>>; 2 * B],
103 }
104
105 impl<K, V> InternalNode<K, V> {
106     /// Creates a new `InternalNode`.
107     ///
108     /// This is unsafe for two reasons. First, it returns an `InternalNode` by value, risking
109     /// dropping of uninitialized fields. Second, an invariant of internal nodes is that `len + 1`
110     /// edges are initialized and valid, meaning that even when the node is empty (having a
111     /// `len` of 0), there must be one initialized and valid edge. This function does not set up
112     /// such an edge.
113     unsafe fn new() -> Self {
114         InternalNode { data: unsafe { LeafNode::new() }, edges: [MaybeUninit::UNINIT; 2 * B] }
115     }
116 }
117
118 /// A managed, non-null pointer to a node. This is either an owned pointer to
119 /// `LeafNode<K, V>` or an owned pointer to `InternalNode<K, V>`.
120 ///
121 /// However, `BoxedNode` contains no information as to which of the two types
122 /// of nodes it actually contains, and, partially due to this lack of information,
123 /// has no destructor.
124 struct BoxedNode<K, V> {
125     ptr: Unique<LeafNode<K, V>>,
126 }
127
128 impl<K, V> BoxedNode<K, V> {
129     fn from_leaf(node: Box<LeafNode<K, V>>) -> Self {
130         BoxedNode { ptr: Box::into_unique(node) }
131     }
132
133     fn from_internal(node: Box<InternalNode<K, V>>) -> Self {
134         BoxedNode { ptr: Box::into_unique(node).cast() }
135     }
136
137     unsafe fn from_ptr(ptr: NonNull<LeafNode<K, V>>) -> Self {
138         BoxedNode { ptr: unsafe { Unique::new_unchecked(ptr.as_ptr()) } }
139     }
140
141     fn as_ptr(&self) -> NonNull<LeafNode<K, V>> {
142         NonNull::from(self.ptr)
143     }
144 }
145
146 /// An owned tree.
147 ///
148 /// Note that this does not have a destructor, and must be cleaned up manually.
149 pub struct Root<K, V> {
150     node: BoxedNode<K, V>,
151     /// The number of levels below the root node.
152     height: usize,
153 }
154
155 unsafe impl<K: Sync, V: Sync> Sync for Root<K, V> {}
156 unsafe impl<K: Send, V: Send> Send for Root<K, V> {}
157
158 impl<K, V> Root<K, V> {
159     /// Returns the number of levels below the root.
160     pub fn height(&self) -> usize {
161         self.height
162     }
163
164     /// Returns a new owned tree, with its own root node that is initially empty.
165     pub fn new_leaf() -> Self {
166         Root { node: BoxedNode::from_leaf(Box::new(unsafe { LeafNode::new() })), height: 0 }
167     }
168
169     /// Borrows and returns an immutable reference to the node owned by the root.
170     pub fn node_as_ref(&self) -> NodeRef<marker::Immut<'_>, K, V, marker::LeafOrInternal> {
171         NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
172     }
173
174     /// Borrows and returns a mutable reference to the node owned by the root.
175     pub fn node_as_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal> {
176         NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
177     }
178
179     pub fn node_as_valmut(&mut self) -> NodeRef<marker::ValMut<'_>, K, V, marker::LeafOrInternal> {
180         NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
181     }
182
183     pub fn into_ref(self) -> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
184         NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
185     }
186
187     /// Adds a new internal node with a single edge, pointing to the previous root, and make that
188     /// new node the root. This increases the height by 1 and is the opposite of
189     /// `pop_internal_level`.
190     pub fn push_internal_level(&mut self) -> NodeRef<marker::Mut<'_>, K, V, marker::Internal> {
191         let mut new_node = Box::new(unsafe { InternalNode::new() });
192         new_node.edges[0].write(unsafe { BoxedNode::from_ptr(self.node.as_ptr()) });
193
194         self.node = BoxedNode::from_internal(new_node);
195         self.height += 1;
196
197         let mut ret =
198             NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData };
199
200         unsafe {
201             ret.reborrow_mut().first_edge().correct_parent_link();
202         }
203
204         ret
205     }
206
207     /// Removes the internal root node, using its first child as the new root node.
208     /// As it is intended only to be called when the root node has only one child,
209     /// no cleanup is done on any of the other children.
210     /// This decreases the height by 1 and is the opposite of `push_internal_level`.
211     ///
212     /// Requires exclusive access to the `Root` object but not to the root node;
213     /// it will not invalidate existing handles or references to the root node.
214     ///
215     /// Panics if there is no internal level, i.e., if the root node is a leaf.
216     pub fn pop_internal_level(&mut self) {
217         assert!(self.height > 0);
218
219         let top = self.node.ptr;
220
221         self.node = unsafe {
222             BoxedNode::from_ptr(
223                 self.node_as_mut().cast_unchecked::<marker::Internal>().first_edge().descend().node,
224             )
225         };
226         self.height -= 1;
227         self.node_as_mut().as_leaf_mut().parent = ptr::null();
228
229         unsafe {
230             Global.dealloc(NonNull::from(top).cast(), Layout::new::<InternalNode<K, V>>());
231         }
232     }
233 }
234
235 // N.B. `NodeRef` is always covariant in `K` and `V`, even when the `BorrowType`
236 // is `Mut`. This is technically wrong, but cannot result in any unsafety due to
237 // internal use of `NodeRef` because we stay completely generic over `K` and `V`.
238 // However, whenever a public type wraps `NodeRef`, make sure that it has the
239 // correct variance.
240 /// A reference to a node.
241 ///
242 /// This type has a number of parameters that controls how it acts:
243 /// - `BorrowType`: This can be `Immut<'a>`, `Mut<'a>` or `ValMut<'a>' for some `'a`
244 ///    or `Owned`.
245 ///    When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`,
246 ///    when this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`,
247 ///    when this is `ValMut<'a>`, the `NodeRef` acts as immutable with respect
248 ///    to keys and tree structure, but allows mutable references to values,
249 ///    and when this is `Owned`, the `NodeRef` acts roughly like `Box<Node>`.
250 /// - `K` and `V`: These control what types of things are stored in the nodes.
251 /// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is
252 ///   `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the
253 ///   `NodeRef` points to an internal node, and when this is `LeafOrInternal` the
254 ///   `NodeRef` could be pointing to either type of node.
255 pub struct NodeRef<BorrowType, K, V, Type> {
256     /// The number of levels below the node.
257     height: usize,
258     node: NonNull<LeafNode<K, V>>,
259     _marker: PhantomData<(BorrowType, Type)>,
260 }
261
262 impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> {}
263 impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
264     fn clone(&self) -> Self {
265         *self
266     }
267 }
268
269 unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync for NodeRef<BorrowType, K, V, Type> {}
270
271 unsafe impl<'a, K: Sync + 'a, V: Sync + 'a, Type> Send for NodeRef<marker::Immut<'a>, K, V, Type> {}
272 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send for NodeRef<marker::Mut<'a>, K, V, Type> {}
273 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send for NodeRef<marker::ValMut<'a>, K, V, Type> {}
274 unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Owned, K, V, Type> {}
275
276 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
277     /// Exposes the data of an internal node for reading.
278     ///
279     /// Returns a raw ptr to avoid invalidating other references to this node,
280     /// which is possible when BorrowType is marker::ValMut.
281     fn as_internal_ptr(&self) -> *const InternalNode<K, V> {
282         self.node.as_ptr() as *const InternalNode<K, V>
283     }
284 }
285
286 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
287     /// Exposes the data of an internal node for reading,
288     /// when we know we have exclusive access.
289     fn as_internal(&mut self) -> &InternalNode<K, V> {
290         unsafe { &*self.as_internal_ptr() }
291     }
292 }
293
294 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
295     /// Exposes the data of an internal node for writing.
296     ///
297     /// We don't need to return a raw ptr because we have unique access to the entire node.
298     fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
299         unsafe { &mut *(self.node.as_ptr() as *mut InternalNode<K, V>) }
300     }
301 }
302
303 impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
304     /// Finds the length of the node. This is the number of keys or values. In an
305     /// internal node, the number of edges is `len() + 1`.
306     /// For any node, the number of possible edge handles is also `len() + 1`.
307     /// Note that, despite being safe, calling this function can have the side effect
308     /// of invalidating mutable references that unsafe code has created.
309     pub fn len(&self) -> usize {
310         // Crucially, we only access the `len` field here. If BorrowType is marker::ValMut,
311         // there might be outstanding mutable references to values that we must not invalidate.
312         unsafe { (*self.as_leaf_ptr()).len as usize }
313     }
314
315     /// Returns the height of this node in the whole tree. Zero height denotes the
316     /// leaf level.
317     pub fn height(&self) -> usize {
318         self.height
319     }
320
321     /// Temporarily takes out another, immutable reference to the same node.
322     fn reborrow(&self) -> NodeRef<marker::Immut<'_>, K, V, Type> {
323         NodeRef { height: self.height, node: self.node, _marker: PhantomData }
324     }
325
326     /// Exposes the leaf "portion" of any leaf or internal node.
327     /// If the node is a leaf, this function simply opens up its data.
328     /// If the node is an internal node, so not a leaf, it does have all the data a leaf has
329     /// (header, keys and values), and this function exposes that.
330     ///
331     /// Returns a raw ptr to avoid invalidating other references to this node,
332     /// which is possible when BorrowType is marker::ValMut.
333     fn as_leaf_ptr(&self) -> *const LeafNode<K, V> {
334         // The node must be valid for at least the LeafNode portion.
335         // This is not a reference in the NodeRef type because we don't know if
336         // it should be unique or shared.
337         self.node.as_ptr()
338     }
339
340     /// Borrows a reference to one of the keys stored in the node.
341     ///
342     /// # Safety
343     /// The node has more than `idx` initialized elements.
344     pub unsafe fn key_at(&self, idx: usize) -> &K {
345         unsafe { self.reborrow().into_key_at(idx) }
346     }
347
348     /// Borrows a reference to one of the values stored in the node.
349     ///
350     /// # Safety
351     /// The node has more than `idx` initialized elements.
352     unsafe fn val_at(&self, idx: usize) -> &V {
353         unsafe { self.reborrow().into_val_at(idx) }
354     }
355
356     /// Finds the parent of the current node. Returns `Ok(handle)` if the current
357     /// node actually has a parent, where `handle` points to the edge of the parent
358     /// that points to the current node. Returns `Err(self)` if the current node has
359     /// no parent, giving back the original `NodeRef`.
360     ///
361     /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
362     /// both, upon success, do nothing.
363     pub fn ascend(
364         self,
365     ) -> Result<Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>, Self> {
366         // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut,
367         // there might be outstanding mutable references to values that we must not invalidate.
368         let parent_as_leaf = unsafe { (*self.as_leaf_ptr()).parent as *const LeafNode<K, V> };
369         if let Some(non_zero) = NonNull::new(parent_as_leaf as *mut _) {
370             Ok(Handle {
371                 node: NodeRef { height: self.height + 1, node: non_zero, _marker: PhantomData },
372                 idx: unsafe { usize::from(*(*self.as_leaf_ptr()).parent_idx.as_ptr()) },
373                 _marker: PhantomData,
374             })
375         } else {
376             Err(self)
377         }
378     }
379
380     pub fn first_edge(self) -> Handle<Self, marker::Edge> {
381         unsafe { Handle::new_edge(self, 0) }
382     }
383
384     pub fn last_edge(self) -> Handle<Self, marker::Edge> {
385         let len = self.len();
386         unsafe { Handle::new_edge(self, len) }
387     }
388
389     /// Note that `self` must be nonempty.
390     pub fn first_kv(self) -> Handle<Self, marker::KV> {
391         let len = self.len();
392         assert!(len > 0);
393         unsafe { Handle::new_kv(self, 0) }
394     }
395
396     /// Note that `self` must be nonempty.
397     pub fn last_kv(self) -> Handle<Self, marker::KV> {
398         let len = self.len();
399         assert!(len > 0);
400         unsafe { Handle::new_kv(self, len - 1) }
401     }
402 }
403
404 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
405     /// Exposes the data of a leaf node for reading in an immutable tree.
406     fn into_leaf(self) -> &'a LeafNode<K, V> {
407         // SAFETY: we can access the entire node freely and do no need raw pointers,
408         // because there can be no mutable references to this Immut tree.
409         unsafe { &(*self.as_leaf_ptr()) }
410     }
411 }
412
413 impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
414     /// Similar to `ascend`, gets a reference to a node's parent node, but also
415     /// deallocate the current node in the process. This is unsafe because the
416     /// current node will still be accessible despite being deallocated.
417     pub unsafe fn deallocate_and_ascend(
418         self,
419     ) -> Option<Handle<NodeRef<marker::Owned, K, V, marker::Internal>, marker::Edge>> {
420         let height = self.height;
421         let node = self.node;
422         let ret = self.ascend().ok();
423         unsafe {
424             Global.dealloc(
425                 node.cast(),
426                 if height > 0 {
427                     Layout::new::<InternalNode<K, V>>()
428                 } else {
429                     Layout::new::<LeafNode<K, V>>()
430                 },
431             );
432         }
433         ret
434     }
435 }
436
437 impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
438     /// Unsafely asserts to the compiler some static information about whether this
439     /// node is a `Leaf` or an `Internal`.
440     unsafe fn cast_unchecked<NewType>(self) -> NodeRef<marker::Mut<'a>, K, V, NewType> {
441         NodeRef { height: self.height, node: self.node, _marker: PhantomData }
442     }
443
444     /// Temporarily takes out another, mutable reference to the same node. Beware, as
445     /// this method is very dangerous, doubly so since it may not immediately appear
446     /// dangerous.
447     ///
448     /// Because mutable pointers can roam anywhere around the tree, the returned
449     /// pointer can easily be used to make the original pointer dangling, out of
450     /// bounds, or invalid under stacked borrow rules.
451     // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef`
452     // that restricts the use of navigation methods on reborrowed pointers,
453     // preventing this unsafety.
454     unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
455         NodeRef { height: self.height, node: self.node, _marker: PhantomData }
456     }
457
458     /// Exposes the leaf "portion" of any leaf or internal node for writing.
459     /// If the node is a leaf, this function simply opens up its data.
460     /// If the node is an internal node, so not a leaf, it does have all the data a leaf has
461     /// (header, keys and values), and this function exposes that.
462     ///
463     /// We don't need to return a raw ptr because we have unique access to the entire node.
464     fn as_leaf_mut(&mut self) -> &'a mut LeafNode<K, V> {
465         unsafe { &mut (*self.node.as_ptr()) }
466     }
467
468     fn keys_mut(&mut self) -> &mut [K] {
469         // SAFETY: the caller will not be able to call further methods on self
470         // until the key slice reference is dropped, as we have unique access
471         // for the lifetime of the borrow.
472         unsafe { self.reborrow_mut().into_key_slice_mut() }
473     }
474
475     fn vals_mut(&mut self) -> &mut [V] {
476         // SAFETY: the caller will not be able to call further methods on self
477         // until the value slice reference is dropped, as we have unique access
478         // for the lifetime of the borrow.
479         unsafe { self.reborrow_mut().into_val_slice_mut() }
480     }
481 }
482
483 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
484     /// # Safety
485     /// The node has more than `idx` initialized elements.
486     unsafe fn into_key_at(self, idx: usize) -> &'a K {
487         unsafe { self.into_leaf().keys.get_unchecked(idx).assume_init_ref() }
488     }
489
490     /// # Safety
491     /// The node has more than `idx` initialized elements.
492     unsafe fn into_val_at(self, idx: usize) -> &'a V {
493         unsafe { self.into_leaf().vals.get_unchecked(idx).assume_init_ref() }
494     }
495 }
496
497 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
498     fn into_key_slice_mut(mut self) -> &'a mut [K] {
499         // SAFETY: The keys of a node must always be initialized up to length.
500         unsafe {
501             slice::from_raw_parts_mut(
502                 MaybeUninit::slice_as_mut_ptr(&mut self.as_leaf_mut().keys),
503                 self.len(),
504             )
505         }
506     }
507
508     fn into_val_slice_mut(mut self) -> &'a mut [V] {
509         // SAFETY: The values of a node must always be initialized up to length.
510         unsafe {
511             slice::from_raw_parts_mut(
512                 MaybeUninit::slice_as_mut_ptr(&mut self.as_leaf_mut().vals),
513                 self.len(),
514             )
515         }
516     }
517
518     /// # Safety
519     /// The node has more than `idx` initialized elements.
520     unsafe fn into_key_mut_at(mut self, idx: usize) -> &'a mut K {
521         debug_assert!(idx < self.len());
522
523         let leaf = self.as_leaf_mut();
524         unsafe { leaf.keys.get_unchecked_mut(idx).assume_init_mut() }
525     }
526
527     /// # Safety
528     /// The node has more than `idx` initialized elements.
529     unsafe fn into_val_mut_at(mut self, idx: usize) -> &'a mut V {
530         debug_assert!(idx < self.len());
531
532         let leaf = self.as_leaf_mut();
533         unsafe { leaf.vals.get_unchecked_mut(idx).assume_init_mut() }
534     }
535 }
536
537 impl<'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(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.node.as_ptr();
545         // We must coerce to unsized array pointers because of Rust issue #74679.
546         let keys: *const [_] = unsafe { &raw const (*leaf).keys };
547         let vals: *mut [_] = unsafe { &raw mut (*leaf).vals };
548         // SAFETY: The keys and values of a node must always be initialized up to length.
549         let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() };
550         let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() };
551         (key, val)
552     }
553 }
554
555 impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
556     /// Adds a key/value pair to the end of the node.
557     pub fn push(&mut self, key: K, val: V) {
558         assert!(self.len() < CAPACITY);
559
560         let idx = self.len();
561
562         unsafe {
563             ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
564             ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
565         }
566         self.as_leaf_mut().len += 1;
567     }
568
569     /// Adds a key/value pair to the beginning of the node.
570     pub fn push_front(&mut self, key: K, val: V) {
571         assert!(self.len() < CAPACITY);
572
573         unsafe {
574             slice_insert(self.keys_mut(), 0, key);
575             slice_insert(self.vals_mut(), 0, val);
576         }
577         self.as_leaf_mut().len += 1;
578     }
579 }
580
581 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
582     /// # Safety
583     /// 'first' and 'after_last' must be in range.
584     unsafe fn correct_childrens_parent_links(&mut self, first: usize, after_last: usize) {
585         debug_assert!(first <= self.len());
586         debug_assert!(after_last <= self.len() + 1);
587         for i in first..after_last {
588             unsafe { Handle::new_edge(self.reborrow_mut(), i) }.correct_parent_link();
589         }
590     }
591
592     fn correct_all_childrens_parent_links(&mut self) {
593         let len = self.len();
594         unsafe { self.correct_childrens_parent_links(0, len + 1) };
595     }
596 }
597
598 impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
599     /// Adds a key/value pair and an edge to go to the right of that pair to
600     /// the end of the node.
601     pub fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
602         assert!(edge.height == self.height - 1);
603         assert!(self.len() < CAPACITY);
604
605         let idx = self.len();
606
607         unsafe {
608             ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
609             ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
610             self.as_internal_mut().edges.get_unchecked_mut(idx + 1).write(edge.node);
611
612             self.as_leaf_mut().len += 1;
613
614             Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
615         }
616     }
617
618     /// Adds a key/value pair and an edge to go to the left of that pair to
619     /// the beginning of the node.
620     pub fn push_front(&mut self, key: K, val: V, edge: Root<K, V>) {
621         assert!(edge.height == self.height - 1);
622         assert!(self.len() < CAPACITY);
623
624         unsafe {
625             slice_insert(self.keys_mut(), 0, key);
626             slice_insert(self.vals_mut(), 0, val);
627             slice_insert(
628                 slice::from_raw_parts_mut(
629                     MaybeUninit::slice_as_mut_ptr(&mut self.as_internal_mut().edges),
630                     self.len() + 1,
631                 ),
632                 0,
633                 edge.node,
634             );
635         }
636
637         self.as_leaf_mut().len += 1;
638
639         self.correct_all_childrens_parent_links();
640     }
641 }
642
643 impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
644     /// Removes a key/value pair from the end of this node and returns the pair.
645     /// If this is an internal node, also removes the edge that was to the right
646     /// of that pair and returns the orphaned node that this edge owned with its
647     /// parent erased.
648     pub fn pop(&mut self) -> (K, V, Option<Root<K, V>>) {
649         assert!(self.len() > 0);
650
651         let idx = self.len() - 1;
652
653         unsafe {
654             let key = ptr::read(self.key_at(idx));
655             let val = ptr::read(self.val_at(idx));
656             let edge = match self.reborrow_mut().force() {
657                 ForceResult::Leaf(_) => None,
658                 ForceResult::Internal(mut internal) => {
659                     let edge =
660                         ptr::read(internal.as_internal().edges.get_unchecked(idx + 1).as_ptr());
661                     let mut new_root = Root { node: edge, height: internal.height - 1 };
662                     new_root.node_as_mut().as_leaf_mut().parent = ptr::null();
663                     Some(new_root)
664                 }
665             };
666
667             self.as_leaf_mut().len -= 1;
668             (key, val, edge)
669         }
670     }
671
672     /// Removes a key/value pair from the beginning of this node. If this is an internal node,
673     /// also removes the edge that was to the left of that pair.
674     pub fn pop_front(&mut self) -> (K, V, Option<Root<K, V>>) {
675         assert!(self.len() > 0);
676
677         let old_len = self.len();
678
679         unsafe {
680             let key = slice_remove(self.keys_mut(), 0);
681             let val = slice_remove(self.vals_mut(), 0);
682             let edge = match self.reborrow_mut().force() {
683                 ForceResult::Leaf(_) => None,
684                 ForceResult::Internal(mut internal) => {
685                     let edge = slice_remove(
686                         slice::from_raw_parts_mut(
687                             MaybeUninit::slice_as_mut_ptr(&mut internal.as_internal_mut().edges),
688                             old_len + 1,
689                         ),
690                         0,
691                     );
692
693                     let mut new_root = Root { node: edge, height: internal.height - 1 };
694                     new_root.node_as_mut().as_leaf_mut().parent = ptr::null();
695
696                     for i in 0..old_len {
697                         Handle::new_edge(internal.reborrow_mut(), i).correct_parent_link();
698                     }
699
700                     Some(new_root)
701                 }
702             };
703
704             self.as_leaf_mut().len -= 1;
705
706             (key, val, edge)
707         }
708     }
709
710     fn into_kv_pointers_mut(mut self) -> (*mut K, *mut V) {
711         (self.keys_mut().as_mut_ptr(), self.vals_mut().as_mut_ptr())
712     }
713 }
714
715 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
716     /// Checks whether a node is an `Internal` node or a `Leaf` node.
717     pub fn force(
718         self,
719     ) -> ForceResult<
720         NodeRef<BorrowType, K, V, marker::Leaf>,
721         NodeRef<BorrowType, K, V, marker::Internal>,
722     > {
723         if self.height == 0 {
724             ForceResult::Leaf(NodeRef {
725                 height: self.height,
726                 node: self.node,
727                 _marker: PhantomData,
728             })
729         } else {
730             ForceResult::Internal(NodeRef {
731                 height: self.height,
732                 node: self.node,
733                 _marker: PhantomData,
734             })
735         }
736     }
737 }
738
739 /// A reference to a specific key/value pair or edge within a node. The `Node` parameter
740 /// must be a `NodeRef`, while the `Type` can either be `KV` (signifying a handle on a key/value
741 /// pair) or `Edge` (signifying a handle on an edge).
742 ///
743 /// Note that even `Leaf` nodes can have `Edge` handles. Instead of representing a pointer to
744 /// a child node, these represent the spaces where child pointers would go between the key/value
745 /// pairs. For example, in a node with length 2, there would be 3 possible edge locations - one
746 /// to the left of the node, one between the two pairs, and one at the right of the node.
747 pub struct Handle<Node, Type> {
748     node: Node,
749     idx: usize,
750     _marker: PhantomData<Type>,
751 }
752
753 impl<Node: Copy, Type> Copy for Handle<Node, Type> {}
754 // We don't need the full generality of `#[derive(Clone)]`, as the only time `Node` will be
755 // `Clone`able is when it is an immutable reference and therefore `Copy`.
756 impl<Node: Copy, Type> Clone for Handle<Node, Type> {
757     fn clone(&self) -> Self {
758         *self
759     }
760 }
761
762 impl<Node, Type> Handle<Node, Type> {
763     /// Retrieves the node that contains the edge or key/value pair this handle points to.
764     pub fn into_node(self) -> Node {
765         self.node
766     }
767
768     /// Returns the position of this handle in the node.
769     pub fn idx(&self) -> usize {
770         self.idx
771     }
772 }
773
774 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
775     /// Creates a new handle to a key/value pair in `node`.
776     /// Unsafe because the caller must ensure that `idx < node.len()`.
777     pub unsafe fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
778         debug_assert!(idx < node.len());
779
780         Handle { node, idx, _marker: PhantomData }
781     }
782
783     pub fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
784         unsafe { Handle::new_edge(self.node, self.idx) }
785     }
786
787     pub fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
788         unsafe { Handle::new_edge(self.node, self.idx + 1) }
789     }
790 }
791
792 impl<BorrowType, K, V, NodeType, HandleType> PartialEq
793     for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
794 {
795     fn eq(&self, other: &Self) -> bool {
796         self.node.node == other.node.node && self.idx == other.idx
797     }
798 }
799
800 impl<BorrowType, K, V, NodeType, HandleType> PartialOrd
801     for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
802 {
803     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
804         if self.node.node == other.node.node { Some(self.idx.cmp(&other.idx)) } else { None }
805     }
806 }
807
808 impl<BorrowType, K, V, NodeType, HandleType>
809     Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
810 {
811     /// Temporarily takes out another, immutable handle on the same location.
812     pub fn reborrow(&self) -> Handle<NodeRef<marker::Immut<'_>, K, V, NodeType>, HandleType> {
813         // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
814         Handle { node: self.node.reborrow(), idx: self.idx, _marker: PhantomData }
815     }
816 }
817
818 impl<'a, K, V, NodeType, HandleType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
819     /// Temporarily takes out another, mutable handle on the same location. Beware, as
820     /// this method is very dangerous, doubly so since it may not immediately appear
821     /// dangerous.
822     ///
823     /// For details, see `NodeRef::reborrow_mut`.
824     pub unsafe fn reborrow_mut(
825         &mut self,
826     ) -> Handle<NodeRef<marker::Mut<'_>, K, V, NodeType>, HandleType> {
827         // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
828         Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData }
829     }
830 }
831
832 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
833     /// Creates a new handle to an edge in `node`.
834     /// Unsafe because the caller must ensure that `idx <= node.len()`.
835     pub unsafe fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
836         debug_assert!(idx <= node.len());
837
838         Handle { node, idx, _marker: PhantomData }
839     }
840
841     pub fn left_kv(self) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
842         if self.idx > 0 {
843             Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) })
844         } else {
845             Err(self)
846         }
847     }
848
849     pub fn right_kv(self) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
850         if self.idx < self.node.len() {
851             Ok(unsafe { Handle::new_kv(self.node, self.idx) })
852         } else {
853             Err(self)
854         }
855     }
856 }
857
858 enum InsertionPlace {
859     Left(usize),
860     Right(usize),
861 }
862
863 /// Given an edge index where we want to insert into a node filled to capacity,
864 /// computes a sensible KV index of a split point and where to perform the insertion.
865 /// The goal of the split point is for its key and value to end up in a parent node;
866 /// the keys, values and edges to the left of the split point become the left child;
867 /// the keys, values and edges to the right of the split point become the right child.
868 fn splitpoint(edge_idx: usize) -> (usize, InsertionPlace) {
869     debug_assert!(edge_idx <= CAPACITY);
870     // Rust issue #74834 tries to explain these symmetric rules.
871     match edge_idx {
872         0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, InsertionPlace::Left(edge_idx)),
873         EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, InsertionPlace::Left(edge_idx)),
874         EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, InsertionPlace::Right(0)),
875         _ => (KV_IDX_CENTER + 1, InsertionPlace::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))),
876     }
877 }
878
879 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::Edge> {
880     /// Helps implementations of `insert_fit` for a particular `NodeType`,
881     /// by taking care of leaf data.
882     /// Inserts a new key/value pair between the key/value pairs to the right and left of
883     /// this edge. This method assumes that there is enough space in the node for the new
884     /// pair to fit.
885     fn leafy_insert_fit(&mut self, key: K, val: V) {
886         // Necessary for correctness, but in a private module
887         debug_assert!(self.node.len() < CAPACITY);
888
889         unsafe {
890             slice_insert(self.node.keys_mut(), self.idx, key);
891             slice_insert(self.node.vals_mut(), self.idx, val);
892
893             self.node.as_leaf_mut().len += 1;
894         }
895     }
896 }
897
898 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
899     /// Inserts a new key/value pair between the key/value pairs to the right and left of
900     /// this edge. This method assumes that there is enough space in the node for the new
901     /// pair to fit.
902     ///
903     /// The returned pointer points to the inserted value.
904     fn insert_fit(&mut self, key: K, val: V) -> *mut V {
905         self.leafy_insert_fit(key, val);
906         unsafe { self.node.vals_mut().get_unchecked_mut(self.idx) }
907     }
908 }
909
910 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
911     /// Inserts a new key/value pair between the key/value pairs to the right and left of
912     /// this edge. This method splits the node if there isn't enough room.
913     ///
914     /// The returned pointer points to the inserted value.
915     fn insert(mut self, key: K, val: V) -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) {
916         if self.node.len() < CAPACITY {
917             let ptr = self.insert_fit(key, val);
918             let kv = unsafe { Handle::new_kv(self.node, self.idx) };
919             (InsertResult::Fit(kv), ptr)
920         } else {
921             let (middle_kv_idx, insertion) = splitpoint(self.idx);
922             let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
923             let (mut left, k, v, mut right) = middle.split();
924             let ptr = match insertion {
925                 InsertionPlace::Left(insert_idx) => unsafe {
926                     Handle::new_edge(left.reborrow_mut(), insert_idx).insert_fit(key, val)
927                 },
928                 InsertionPlace::Right(insert_idx) => unsafe {
929                     Handle::new_edge(
930                         right.node_as_mut().cast_unchecked::<marker::Leaf>(),
931                         insert_idx,
932                     )
933                     .insert_fit(key, val)
934                 },
935             };
936             (InsertResult::Split(SplitResult { left: left.forget_type(), k, v, right }), ptr)
937         }
938     }
939 }
940
941 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
942     /// Fixes the parent pointer and index in the child node below this edge. This is useful
943     /// when the ordering of edges has been changed, such as in the various `insert` methods.
944     fn correct_parent_link(mut self) {
945         let idx = self.idx as u16;
946         let ptr = self.node.as_internal_mut() as *mut _;
947         let mut child = self.descend();
948         child.as_leaf_mut().parent = ptr;
949         child.as_leaf_mut().parent_idx.write(idx);
950     }
951 }
952
953 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
954     /// Inserts a new key/value pair and an edge that will go to the right of that new pair
955     /// between this edge and the key/value pair to the right of this edge. This method assumes
956     /// that there is enough space in the node for the new pair to fit.
957     fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
958         // Necessary for correctness, but in an internal module
959         debug_assert!(self.node.len() < CAPACITY);
960         debug_assert!(edge.height == self.node.height - 1);
961
962         unsafe {
963             self.leafy_insert_fit(key, val);
964
965             slice_insert(
966                 slice::from_raw_parts_mut(
967                     MaybeUninit::slice_as_mut_ptr(&mut self.node.as_internal_mut().edges),
968                     self.node.len(),
969                 ),
970                 self.idx + 1,
971                 edge.node,
972             );
973
974             for i in (self.idx + 1)..(self.node.len() + 1) {
975                 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
976             }
977         }
978     }
979
980     /// Inserts a new key/value pair and an edge that will go to the right of that new pair
981     /// between this edge and the key/value pair to the right of this edge. This method splits
982     /// the node if there isn't enough room.
983     fn insert(
984         mut self,
985         key: K,
986         val: V,
987         edge: Root<K, V>,
988     ) -> InsertResult<'a, K, V, marker::Internal> {
989         assert!(edge.height == self.node.height - 1);
990
991         if self.node.len() < CAPACITY {
992             self.insert_fit(key, val, edge);
993             let kv = unsafe { Handle::new_kv(self.node, self.idx) };
994             InsertResult::Fit(kv)
995         } else {
996             let (middle_kv_idx, insertion) = splitpoint(self.idx);
997             let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
998             let (mut left, k, v, mut right) = middle.split();
999             match insertion {
1000                 InsertionPlace::Left(insert_idx) => unsafe {
1001                     Handle::new_edge(left.reborrow_mut(), insert_idx).insert_fit(key, val, edge);
1002                 },
1003                 InsertionPlace::Right(insert_idx) => unsafe {
1004                     Handle::new_edge(
1005                         right.node_as_mut().cast_unchecked::<marker::Internal>(),
1006                         insert_idx,
1007                     )
1008                     .insert_fit(key, val, edge);
1009                 },
1010             }
1011             InsertResult::Split(SplitResult { left: left.forget_type(), k, v, right })
1012         }
1013     }
1014 }
1015
1016 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
1017     /// Inserts a new key/value pair between the key/value pairs to the right and left of
1018     /// this edge. This method splits the node if there isn't enough room, and tries to
1019     /// insert the split off portion into the parent node recursively, until the root is reached.
1020     ///
1021     /// If the returned result is a `Fit`, its handle's node can be this edge's node or an ancestor.
1022     /// If the returned result is a `Split`, the `left` field will be the root node.
1023     /// The returned pointer points to the inserted value.
1024     pub fn insert_recursing(
1025         self,
1026         key: K,
1027         value: V,
1028     ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) {
1029         let (mut split, val_ptr) = match self.insert(key, value) {
1030             (InsertResult::Fit(handle), ptr) => {
1031                 return (InsertResult::Fit(handle.forget_node_type()), ptr);
1032             }
1033             (InsertResult::Split(split), val_ptr) => (split, val_ptr),
1034         };
1035
1036         loop {
1037             split = match split.left.ascend() {
1038                 Ok(parent) => match parent.insert(split.k, split.v, split.right) {
1039                     InsertResult::Fit(handle) => {
1040                         return (InsertResult::Fit(handle.forget_node_type()), val_ptr);
1041                     }
1042                     InsertResult::Split(split) => split,
1043                 },
1044                 Err(root) => {
1045                     return (InsertResult::Split(SplitResult { left: root, ..split }), val_ptr);
1046                 }
1047             };
1048         }
1049     }
1050 }
1051
1052 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1053     /// Finds the node pointed to by this edge.
1054     ///
1055     /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
1056     /// both, upon success, do nothing.
1057     pub fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1058         // We need to use raw pointers to nodes because, if BorrowType is
1059         // marker::ValMut, there might be outstanding mutable references to
1060         // values that we must not invalidate. There's no worry accessing the
1061         // height field because that value is copied. Beware that, once the
1062         // node pointer is dereferenced, we access the edges array with a
1063         // reference (Rust issue #73987) and invalidate any other references
1064         // to or inside the array, should any be around.
1065         let internal_node = self.node.as_internal_ptr();
1066         NodeRef {
1067             height: self.node.height - 1,
1068             node: unsafe { (&*(*internal_node).edges.get_unchecked(self.idx).as_ptr()).as_ptr() },
1069             _marker: PhantomData,
1070         }
1071     }
1072 }
1073
1074 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
1075     pub fn into_kv(self) -> (&'a K, &'a V) {
1076         (unsafe { self.node.into_key_at(self.idx) }, unsafe { self.node.into_val_at(self.idx) })
1077     }
1078 }
1079
1080 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1081     pub fn into_key_mut(self) -> &'a mut K {
1082         unsafe { self.node.into_key_mut_at(self.idx) }
1083     }
1084
1085     pub fn into_val_mut(self) -> &'a mut V {
1086         unsafe { self.node.into_val_mut_at(self.idx) }
1087     }
1088 }
1089
1090 impl<'a, K, V, NodeType> Handle<NodeRef<marker::ValMut<'a>, K, V, NodeType>, marker::KV> {
1091     pub fn into_kv_valmut(self) -> (&'a K, &'a mut V) {
1092         unsafe { self.node.into_key_val_mut_at(self.idx) }
1093     }
1094 }
1095
1096 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1097     pub fn kv_mut(&mut self) -> (&mut K, &mut V) {
1098         // We cannot call into_key_mut_at and into_val_mut_at, because calling the second one
1099         // invalidates the reference returned by the first.
1100         let leaf = self.node.as_leaf_mut();
1101         let key = unsafe { leaf.keys.get_unchecked_mut(self.idx).assume_init_mut() };
1102         let val = unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() };
1103         (key, val)
1104     }
1105 }
1106
1107 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1108     /// Helps implementations of `split` for a particular `NodeType`,
1109     /// by taking care of leaf data.
1110     fn leafy_split(&mut self, new_node: &mut LeafNode<K, V>) -> (K, V, usize) {
1111         unsafe {
1112             let k = ptr::read(self.node.key_at(self.idx));
1113             let v = ptr::read(self.node.val_at(self.idx));
1114
1115             let new_len = self.node.len() - self.idx - 1;
1116
1117             ptr::copy_nonoverlapping(
1118                 self.node.key_at(self.idx + 1),
1119                 new_node.keys.as_mut_ptr() as *mut K,
1120                 new_len,
1121             );
1122             ptr::copy_nonoverlapping(
1123                 self.node.val_at(self.idx + 1),
1124                 new_node.vals.as_mut_ptr() as *mut V,
1125                 new_len,
1126             );
1127
1128             self.node.as_leaf_mut().len = self.idx as u16;
1129             new_node.len = new_len as u16;
1130             (k, v, new_len)
1131         }
1132     }
1133 }
1134
1135 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1136     /// Splits the underlying node into three parts:
1137     ///
1138     /// - The node is truncated to only contain the key/value pairs to the right of
1139     ///   this handle.
1140     /// - The key and value pointed to by this handle and extracted.
1141     /// - All the key/value pairs to the right of this handle are put into a newly
1142     ///   allocated node.
1143     pub fn split(mut self) -> (NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, K, V, Root<K, V>) {
1144         unsafe {
1145             let mut new_node = Box::new(LeafNode::new());
1146
1147             let (k, v, _) = self.leafy_split(&mut new_node);
1148
1149             (self.node, k, v, Root { node: BoxedNode::from_leaf(new_node), height: 0 })
1150         }
1151     }
1152
1153     /// Removes the key/value pair pointed to by this handle and returns it, along with the edge
1154     /// that the key/value pair collapsed into.
1155     pub fn remove(
1156         mut self,
1157     ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
1158         unsafe {
1159             let k = slice_remove(self.node.keys_mut(), self.idx);
1160             let v = slice_remove(self.node.vals_mut(), self.idx);
1161             self.node.as_leaf_mut().len -= 1;
1162             ((k, v), self.left_edge())
1163         }
1164     }
1165 }
1166
1167 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1168     /// Returns `true` if it is valid to call `.merge()`, i.e., whether there is enough room in
1169     /// a node to hold the combination of the nodes to the left and right of this handle along
1170     /// with the key/value pair at this handle.
1171     pub fn can_merge(&self) -> bool {
1172         (self.reborrow().left_edge().descend().len()
1173             + self.reborrow().right_edge().descend().len()
1174             + 1)
1175             <= CAPACITY
1176     }
1177 }
1178
1179 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1180     /// Splits the underlying node into three parts:
1181     ///
1182     /// - The node is truncated to only contain the edges and key/value pairs to the
1183     ///   right of this handle.
1184     /// - The key and value pointed to by this handle and extracted.
1185     /// - All the edges and key/value pairs to the right of this handle are put into
1186     ///   a newly allocated node.
1187     pub fn split(mut self) -> (NodeRef<marker::Mut<'a>, K, V, marker::Internal>, K, V, Root<K, V>) {
1188         unsafe {
1189             let mut new_node = Box::new(InternalNode::new());
1190
1191             let (k, v, new_len) = self.leafy_split(&mut new_node.data);
1192             let height = self.node.height;
1193             let old_node = &*self.node.as_internal_ptr();
1194
1195             ptr::copy_nonoverlapping(
1196                 old_node.edges.as_ptr().add(self.idx + 1),
1197                 new_node.edges.as_mut_ptr(),
1198                 new_len + 1,
1199             );
1200
1201             let mut new_root = Root { node: BoxedNode::from_internal(new_node), height };
1202
1203             for i in 0..(new_len + 1) {
1204                 Handle::new_edge(new_root.node_as_mut().cast_unchecked(), i).correct_parent_link();
1205             }
1206
1207             (self.node, k, v, new_root)
1208         }
1209     }
1210
1211     /// Combines the node immediately to the left of this handle, the key/value pair pointed
1212     /// to by this handle, and the node immediately to the right of this handle into one new
1213     /// child of the underlying node, returning an edge referencing that new child.
1214     ///
1215     /// Panics unless this edge `.can_merge()`.
1216     pub fn merge(
1217         mut self,
1218     ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1219         let self1 = unsafe { ptr::read(&self) };
1220         let self2 = unsafe { ptr::read(&self) };
1221         let mut left_node = self1.left_edge().descend();
1222         let left_len = left_node.len();
1223         let right_node = self2.right_edge().descend();
1224         let right_len = right_node.len();
1225
1226         assert!(left_len + right_len < CAPACITY);
1227
1228         unsafe {
1229             ptr::write(
1230                 left_node.keys_mut().get_unchecked_mut(left_len),
1231                 slice_remove(self.node.keys_mut(), self.idx),
1232             );
1233             ptr::copy_nonoverlapping(
1234                 right_node.key_at(0),
1235                 left_node.keys_mut().as_mut_ptr().add(left_len + 1),
1236                 right_len,
1237             );
1238             ptr::write(
1239                 left_node.vals_mut().get_unchecked_mut(left_len),
1240                 slice_remove(self.node.vals_mut(), self.idx),
1241             );
1242             ptr::copy_nonoverlapping(
1243                 right_node.val_at(0),
1244                 left_node.vals_mut().as_mut_ptr().add(left_len + 1),
1245                 right_len,
1246             );
1247
1248             slice_remove(&mut self.node.as_internal_mut().edges, self.idx + 1);
1249             for i in self.idx + 1..self.node.len() {
1250                 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
1251             }
1252             self.node.as_leaf_mut().len -= 1;
1253
1254             left_node.as_leaf_mut().len += right_len as u16 + 1;
1255
1256             if self.node.height > 1 {
1257                 // SAFETY: the height of the nodes being merged is one below the height
1258                 // of the node of this edge, thus above zero, so they are internal.
1259                 let mut left_node = left_node.cast_unchecked();
1260                 let mut right_node = right_node.cast_unchecked();
1261                 ptr::copy_nonoverlapping(
1262                     right_node.as_internal().edges.as_ptr(),
1263                     left_node.as_internal_mut().edges.as_mut_ptr().add(left_len + 1),
1264                     right_len + 1,
1265                 );
1266
1267                 for i in left_len + 1..left_len + right_len + 2 {
1268                     Handle::new_edge(left_node.reborrow_mut(), i).correct_parent_link();
1269                 }
1270
1271                 Global.dealloc(right_node.node.cast(), Layout::new::<InternalNode<K, V>>());
1272             } else {
1273                 Global.dealloc(right_node.node.cast(), Layout::new::<LeafNode<K, V>>());
1274             }
1275
1276             Handle::new_edge(self.node, self.idx)
1277         }
1278     }
1279
1280     /// This removes a key/value pair from the left child and places it in the key/value storage
1281     /// pointed to by this handle while pushing the old key/value pair of this handle into the right
1282     /// child.
1283     pub fn steal_left(&mut self) {
1284         unsafe {
1285             let (k, v, edge) = self.reborrow_mut().left_edge().descend().pop();
1286
1287             let k = mem::replace(self.kv_mut().0, k);
1288             let v = mem::replace(self.kv_mut().1, v);
1289
1290             match self.reborrow_mut().right_edge().descend().force() {
1291                 ForceResult::Leaf(mut leaf) => leaf.push_front(k, v),
1292                 ForceResult::Internal(mut internal) => internal.push_front(k, v, edge.unwrap()),
1293             }
1294         }
1295     }
1296
1297     /// This removes a key/value pair from the right child and places it in the key/value storage
1298     /// pointed to by this handle while pushing the old key/value pair of this handle into the left
1299     /// child.
1300     pub fn steal_right(&mut self) {
1301         unsafe {
1302             let (k, v, edge) = self.reborrow_mut().right_edge().descend().pop_front();
1303
1304             let k = mem::replace(self.kv_mut().0, k);
1305             let v = mem::replace(self.kv_mut().1, v);
1306
1307             match self.reborrow_mut().left_edge().descend().force() {
1308                 ForceResult::Leaf(mut leaf) => leaf.push(k, v),
1309                 ForceResult::Internal(mut internal) => internal.push(k, v, edge.unwrap()),
1310             }
1311         }
1312     }
1313
1314     /// This does stealing similar to `steal_left` but steals multiple elements at once.
1315     pub fn bulk_steal_left(&mut self, count: usize) {
1316         unsafe {
1317             let mut left_node = ptr::read(self).left_edge().descend();
1318             let left_len = left_node.len();
1319             let mut right_node = ptr::read(self).right_edge().descend();
1320             let right_len = right_node.len();
1321
1322             // Make sure that we may steal safely.
1323             assert!(right_len + count <= CAPACITY);
1324             assert!(left_len >= count);
1325
1326             let new_left_len = left_len - count;
1327
1328             // Move data.
1329             {
1330                 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1331                 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1332                 let parent_kv = {
1333                     let kv = self.kv_mut();
1334                     (kv.0 as *mut K, kv.1 as *mut V)
1335                 };
1336
1337                 // Make room for stolen elements in the right child.
1338                 ptr::copy(right_kv.0, right_kv.0.add(count), right_len);
1339                 ptr::copy(right_kv.1, right_kv.1.add(count), right_len);
1340
1341                 // Move elements from the left child to the right one.
1342                 move_kv(left_kv, new_left_len + 1, right_kv, 0, count - 1);
1343
1344                 // Move parent's key/value pair to the right child.
1345                 move_kv(parent_kv, 0, right_kv, count - 1, 1);
1346
1347                 // Move the left-most stolen pair to the parent.
1348                 move_kv(left_kv, new_left_len, parent_kv, 0, 1);
1349             }
1350
1351             left_node.as_leaf_mut().len -= count as u16;
1352             right_node.as_leaf_mut().len += count as u16;
1353
1354             match (left_node.force(), right_node.force()) {
1355                 (ForceResult::Internal(left), ForceResult::Internal(mut right)) => {
1356                     // Make room for stolen edges.
1357                     let right_edges = right.reborrow_mut().as_internal_mut().edges.as_mut_ptr();
1358                     ptr::copy(right_edges, right_edges.add(count), right_len + 1);
1359                     right.correct_childrens_parent_links(count, count + right_len + 1);
1360
1361                     move_edges(left, new_left_len + 1, right, 0, count);
1362                 }
1363                 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1364                 _ => {
1365                     unreachable!();
1366                 }
1367             }
1368         }
1369     }
1370
1371     /// The symmetric clone of `bulk_steal_left`.
1372     pub fn bulk_steal_right(&mut self, count: usize) {
1373         unsafe {
1374             let mut left_node = ptr::read(self).left_edge().descend();
1375             let left_len = left_node.len();
1376             let mut right_node = ptr::read(self).right_edge().descend();
1377             let right_len = right_node.len();
1378
1379             // Make sure that we may steal safely.
1380             assert!(left_len + count <= CAPACITY);
1381             assert!(right_len >= count);
1382
1383             let new_right_len = right_len - count;
1384
1385             // Move data.
1386             {
1387                 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1388                 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1389                 let parent_kv = {
1390                     let kv = self.kv_mut();
1391                     (kv.0 as *mut K, kv.1 as *mut V)
1392                 };
1393
1394                 // Move parent's key/value pair to the left child.
1395                 move_kv(parent_kv, 0, left_kv, left_len, 1);
1396
1397                 // Move elements from the right child to the left one.
1398                 move_kv(right_kv, 0, left_kv, left_len + 1, count - 1);
1399
1400                 // Move the right-most stolen pair to the parent.
1401                 move_kv(right_kv, count - 1, parent_kv, 0, 1);
1402
1403                 // Fix right indexing
1404                 ptr::copy(right_kv.0.add(count), right_kv.0, new_right_len);
1405                 ptr::copy(right_kv.1.add(count), right_kv.1, new_right_len);
1406             }
1407
1408             left_node.as_leaf_mut().len += count as u16;
1409             right_node.as_leaf_mut().len -= count as u16;
1410
1411             match (left_node.force(), right_node.force()) {
1412                 (ForceResult::Internal(left), ForceResult::Internal(mut right)) => {
1413                     move_edges(right.reborrow_mut(), 0, left, left_len + 1, count);
1414
1415                     // Fix right indexing.
1416                     let right_edges = right.reborrow_mut().as_internal_mut().edges.as_mut_ptr();
1417                     ptr::copy(right_edges.add(count), right_edges, new_right_len + 1);
1418                     right.correct_childrens_parent_links(0, new_right_len + 1);
1419                 }
1420                 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1421                 _ => {
1422                     unreachable!();
1423                 }
1424             }
1425         }
1426     }
1427 }
1428
1429 unsafe fn move_kv<K, V>(
1430     source: (*mut K, *mut V),
1431     source_offset: usize,
1432     dest: (*mut K, *mut V),
1433     dest_offset: usize,
1434     count: usize,
1435 ) {
1436     unsafe {
1437         ptr::copy_nonoverlapping(source.0.add(source_offset), dest.0.add(dest_offset), count);
1438         ptr::copy_nonoverlapping(source.1.add(source_offset), dest.1.add(dest_offset), count);
1439     }
1440 }
1441
1442 // Source and destination must have the same height.
1443 unsafe fn move_edges<K, V>(
1444     mut source: NodeRef<marker::Mut<'_>, K, V, marker::Internal>,
1445     source_offset: usize,
1446     mut dest: NodeRef<marker::Mut<'_>, K, V, marker::Internal>,
1447     dest_offset: usize,
1448     count: usize,
1449 ) {
1450     let source_ptr = source.as_internal().edges.as_ptr();
1451     let dest_ptr = dest.as_internal_mut().edges.as_mut_ptr();
1452     unsafe {
1453         ptr::copy_nonoverlapping(source_ptr.add(source_offset), dest_ptr.add(dest_offset), count);
1454         dest.correct_childrens_parent_links(dest_offset, dest_offset + count);
1455     }
1456 }
1457
1458 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Leaf> {
1459     /// Removes any static information asserting that this node is a `Leaf` node.
1460     pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1461         NodeRef { height: self.height, node: self.node, _marker: PhantomData }
1462     }
1463 }
1464
1465 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
1466     /// Removes any static information asserting that this node is an `Internal` node.
1467     pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1468         NodeRef { height: self.height, node: self.node, _marker: PhantomData }
1469     }
1470 }
1471
1472 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1473     pub fn forget_node_type(
1474         self,
1475     ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1476         unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1477     }
1478 }
1479
1480 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1481     pub fn forget_node_type(
1482         self,
1483     ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1484         unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1485     }
1486 }
1487
1488 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::KV> {
1489     pub fn forget_node_type(
1490         self,
1491     ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1492         unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1493     }
1494 }
1495
1496 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::KV> {
1497     pub fn forget_node_type(
1498         self,
1499     ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1500         unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1501     }
1502 }
1503
1504 impl<BorrowType, K, V, HandleType>
1505     Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, HandleType>
1506 {
1507     /// Checks whether the underlying node is an `Internal` node or a `Leaf` node.
1508     pub fn force(
1509         self,
1510     ) -> ForceResult<
1511         Handle<NodeRef<BorrowType, K, V, marker::Leaf>, HandleType>,
1512         Handle<NodeRef<BorrowType, K, V, marker::Internal>, HandleType>,
1513     > {
1514         match self.node.force() {
1515             ForceResult::Leaf(node) => {
1516                 ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData })
1517             }
1518             ForceResult::Internal(node) => {
1519                 ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData })
1520             }
1521         }
1522     }
1523 }
1524
1525 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1526     /// Move the suffix after `self` from one node to another one. `right` must be empty.
1527     /// The first edge of `right` remains unchanged.
1528     pub fn move_suffix(
1529         &mut self,
1530         right: &mut NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1531     ) {
1532         unsafe {
1533             let left_new_len = self.idx;
1534             let mut left_node = self.reborrow_mut().into_node();
1535
1536             let right_new_len = left_node.len() - left_new_len;
1537             let mut right_node = right.reborrow_mut();
1538
1539             assert!(right_node.len() == 0);
1540             assert!(left_node.height == right_node.height);
1541
1542             if right_new_len > 0 {
1543                 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1544                 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1545
1546                 move_kv(left_kv, left_new_len, right_kv, 0, right_new_len);
1547
1548                 left_node.as_leaf_mut().len = left_new_len as u16;
1549                 right_node.as_leaf_mut().len = right_new_len as u16;
1550
1551                 match (left_node.force(), right_node.force()) {
1552                     (ForceResult::Internal(left), ForceResult::Internal(right)) => {
1553                         move_edges(left, left_new_len + 1, right, 1, right_new_len);
1554                     }
1555                     (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1556                     _ => {
1557                         unreachable!();
1558                     }
1559                 }
1560             }
1561         }
1562     }
1563 }
1564
1565 pub enum ForceResult<Leaf, Internal> {
1566     Leaf(Leaf),
1567     Internal(Internal),
1568 }
1569
1570 /// Result of insertion, when a node needed to expand beyond its capacity.
1571 /// Does not distinguish between `Leaf` and `Internal` because `Root` doesn't.
1572 pub struct SplitResult<'a, K, V> {
1573     // Altered node in existing tree with elements and edges that belong to the left of `k`.
1574     pub left: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1575     // Some key and value split off, to be inserted elsewhere.
1576     pub k: K,
1577     pub v: V,
1578     // Owned, unattached, new node with elements and edges that belong to the right of `k`.
1579     pub right: Root<K, V>,
1580 }
1581
1582 pub enum InsertResult<'a, K, V, Type> {
1583     Fit(Handle<NodeRef<marker::Mut<'a>, K, V, Type>, marker::KV>),
1584     Split(SplitResult<'a, K, V>),
1585 }
1586
1587 pub mod marker {
1588     use core::marker::PhantomData;
1589
1590     pub enum Leaf {}
1591     pub enum Internal {}
1592     pub enum LeafOrInternal {}
1593
1594     pub enum Owned {}
1595     pub struct Immut<'a>(PhantomData<&'a ()>);
1596     pub struct Mut<'a>(PhantomData<&'a mut ()>);
1597     pub struct ValMut<'a>(PhantomData<&'a mut ()>);
1598
1599     pub enum KV {}
1600     pub enum Edge {}
1601 }
1602
1603 unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
1604     unsafe {
1605         ptr::copy(slice.as_ptr().add(idx), slice.as_mut_ptr().add(idx + 1), slice.len() - idx);
1606         ptr::write(slice.get_unchecked_mut(idx), val);
1607     }
1608 }
1609
1610 unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
1611     unsafe {
1612         let ret = ptr::read(slice.get_unchecked(idx));
1613         ptr::copy(slice.as_ptr().add(idx + 1), slice.as_mut_ptr().add(idx), slice.len() - idx - 1);
1614         ret
1615     }
1616 }
1617
1618 #[cfg(test)]
1619 mod tests;