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