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