1 // This is an attempt at an implementation following the ideal
4 // struct BTreeMap<K, V> {
6 // root: Option<Box<Node<K, V, height>>>
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]
15 // parent: *const Node<K, V, height + 1>,
21 // Since Rust doesn't actually have dependent types and polymorphic recursion,
22 // we make do with lots of unsafety.
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:
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.
34 use core::cmp::Ordering;
35 use core::marker::PhantomData;
36 use core::mem::{self, MaybeUninit};
37 use core::ptr::{self, NonNull, Unique};
40 use crate::alloc::{AllocRef, Global, Layout};
41 use crate::boxed::Box;
44 pub const MIN_LEN: usize = B - 1;
45 pub const CAPACITY: usize = 2 * B - 1;
46 const KV_IDX_CENTER: usize = B - 1;
47 const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1;
48 const EDGE_IDX_RIGHT_OF_CENTER: usize = B;
50 /// The underlying representation of leaf nodes.
52 struct LeafNode<K, V> {
53 /// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`.
54 /// This either points to an actual node or is null.
55 parent: *const InternalNode<K, V>,
57 /// This node's index into the parent node's `edges` array.
58 /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`.
59 /// This is only guaranteed to be initialized when `parent` is non-null.
60 parent_idx: MaybeUninit<u16>,
62 /// The number of keys and values this node stores.
64 /// This next to `parent_idx` to encourage the compiler to join `len` and
65 /// `parent_idx` into the same 32-bit word, reducing space overhead.
68 /// The arrays storing the actual data of the node. Only the first `len` elements of each
69 /// array are initialized and valid.
70 keys: [MaybeUninit<K>; CAPACITY],
71 vals: [MaybeUninit<V>; CAPACITY],
74 impl<K, V> LeafNode<K, V> {
75 /// Creates a new `LeafNode`. Unsafe because all nodes should really be hidden behind
76 /// `BoxedNode`, preventing accidental dropping of uninitialized keys and values.
77 unsafe fn new() -> Self {
79 // As a general policy, we leave fields uninitialized if they can be, as this should
80 // be both slightly faster and easier to track in Valgrind.
81 keys: [MaybeUninit::UNINIT; CAPACITY],
82 vals: [MaybeUninit::UNINIT; CAPACITY],
84 parent_idx: MaybeUninit::uninit(),
90 /// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden
91 /// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an
92 /// `InternalNode` can be directly casted to a pointer to the underlying `LeafNode` portion of the
93 /// node, allowing code to act on leaf and internal nodes generically without having to even check
94 /// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`.
96 struct InternalNode<K, V> {
99 /// The pointers to the children of this node. `len + 1` of these are considered
100 /// initialized and valid. Although during the process of `into_iter` or `drop`,
101 /// some pointers are dangling while others still need to be traversed.
102 edges: [MaybeUninit<BoxedNode<K, V>>; 2 * B],
105 impl<K, V> InternalNode<K, V> {
106 /// Creates a new `InternalNode`.
108 /// This is unsafe for two reasons. First, it returns an `InternalNode` by value, risking
109 /// dropping of uninitialized fields. Second, an invariant of internal nodes is that `len + 1`
110 /// edges are initialized and valid, meaning that even when the node is empty (having a
111 /// `len` of 0), there must be one initialized and valid edge. This function does not set up
113 unsafe fn new() -> Self {
114 InternalNode { data: unsafe { LeafNode::new() }, edges: [MaybeUninit::UNINIT; 2 * B] }
118 /// A managed, non-null pointer to a node. This is either an owned pointer to
119 /// `LeafNode<K, V>` or an owned pointer to `InternalNode<K, V>`.
121 /// However, `BoxedNode` contains no information as to which of the two types
122 /// of nodes it actually contains, and, partially due to this lack of information,
123 /// has no destructor.
124 struct BoxedNode<K, V> {
125 ptr: Unique<LeafNode<K, V>>,
128 impl<K, V> BoxedNode<K, V> {
129 fn from_leaf(node: Box<LeafNode<K, V>>) -> Self {
130 BoxedNode { ptr: Box::into_unique(node) }
133 fn from_internal(node: Box<InternalNode<K, V>>) -> Self {
134 BoxedNode { ptr: Box::into_unique(node).cast() }
137 unsafe fn from_ptr(ptr: NonNull<LeafNode<K, V>>) -> Self {
138 BoxedNode { ptr: unsafe { Unique::new_unchecked(ptr.as_ptr()) } }
141 fn as_ptr(&self) -> NonNull<LeafNode<K, V>> {
142 NonNull::from(self.ptr)
148 /// Note that this does not have a destructor, and must be cleaned up manually.
149 pub struct Root<K, V> {
150 node: BoxedNode<K, V>,
151 /// The number of levels below the root node.
155 unsafe impl<K: Sync, V: Sync> Sync for Root<K, V> {}
156 unsafe impl<K: Send, V: Send> Send for Root<K, V> {}
158 impl<K, V> Root<K, V> {
159 /// Returns the number of levels below the root.
160 pub fn height(&self) -> usize {
164 /// Returns a new owned tree, with its own root node that is initially empty.
165 pub fn new_leaf() -> Self {
166 Root { node: BoxedNode::from_leaf(Box::new(unsafe { LeafNode::new() })), height: 0 }
169 /// Borrows and returns an immutable reference to the node owned by the root.
170 pub fn node_as_ref(&self) -> NodeRef<marker::Immut<'_>, K, V, marker::LeafOrInternal> {
171 NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
174 /// Borrows and returns a mutable reference to the node owned by the root.
175 pub fn node_as_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal> {
176 NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
179 pub fn node_as_valmut(&mut self) -> NodeRef<marker::ValMut<'_>, K, V, marker::LeafOrInternal> {
180 NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
183 pub fn into_ref(self) -> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
184 NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData }
187 /// Adds a new internal node with a single edge, pointing to the previous root, and make that
188 /// new node the root. This increases the height by 1 and is the opposite of
189 /// `pop_internal_level`.
190 pub fn push_internal_level(&mut self) -> NodeRef<marker::Mut<'_>, K, V, marker::Internal> {
191 let mut new_node = Box::new(unsafe { InternalNode::new() });
192 new_node.edges[0].write(unsafe { BoxedNode::from_ptr(self.node.as_ptr()) });
194 self.node = BoxedNode::from_internal(new_node);
198 NodeRef { height: self.height, node: self.node.as_ptr(), _marker: PhantomData };
201 ret.reborrow_mut().first_edge().correct_parent_link();
207 /// Removes the internal root node, using its first child as the new root node.
208 /// As it is intended only to be called when the root node has only one child,
209 /// no cleanup is done on any of the other children.
210 /// This decreases the height by 1 and is the opposite of `push_internal_level`.
212 /// Requires exclusive access to the `Root` object but not to the root node;
213 /// it will not invalidate existing handles or references to the root node.
215 /// Panics if there is no internal level, i.e., if the root node is a leaf.
216 pub fn pop_internal_level(&mut self) {
217 assert!(self.height > 0);
219 let top = self.node.ptr;
223 self.node_as_mut().cast_unchecked::<marker::Internal>().first_edge().descend().node,
227 self.node_as_mut().as_leaf_mut().parent = ptr::null();
230 Global.dealloc(NonNull::from(top).cast(), Layout::new::<InternalNode<K, V>>());
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
240 /// A reference to a node.
242 /// This type has a number of parameters that controls how it acts:
243 /// - `BorrowType`: This can be `Immut<'a>`, `Mut<'a>` or `ValMut<'a>' for some `'a`
245 /// When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`,
246 /// when this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`,
247 /// when this is `ValMut<'a>`, the `NodeRef` acts as immutable with respect
248 /// to keys and tree structure, but allows mutable references to values,
249 /// and when this is `Owned`, the `NodeRef` acts roughly like `Box<Node>`.
250 /// - `K` and `V`: These control what types of things are stored in the nodes.
251 /// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is
252 /// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the
253 /// `NodeRef` points to an internal node, and when this is `LeafOrInternal` the
254 /// `NodeRef` could be pointing to either type of node.
255 pub struct NodeRef<BorrowType, K, V, Type> {
256 /// The number of levels below the node.
258 node: NonNull<LeafNode<K, V>>,
259 _marker: PhantomData<(BorrowType, Type)>,
262 impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> {}
263 impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
264 fn clone(&self) -> Self {
269 unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync for NodeRef<BorrowType, K, V, Type> {}
271 unsafe impl<'a, K: Sync + 'a, V: Sync + 'a, Type> Send for NodeRef<marker::Immut<'a>, K, V, Type> {}
272 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send for NodeRef<marker::Mut<'a>, K, V, Type> {}
273 unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send for NodeRef<marker::ValMut<'a>, K, V, Type> {}
274 unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Owned, K, V, Type> {}
276 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
277 /// Exposes the data of an internal node for reading.
279 /// Returns a raw ptr to avoid invalidating other references to this node,
280 /// which is possible when BorrowType is marker::ValMut.
281 fn as_internal_ptr(&self) -> *const InternalNode<K, V> {
282 self.node.as_ptr() as *const InternalNode<K, V>
286 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
287 /// Exposes the data of an internal node for reading,
288 /// when we know we have exclusive access.
289 fn as_internal(&mut self) -> &InternalNode<K, V> {
290 unsafe { &*self.as_internal_ptr() }
294 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
295 /// Exposes the data of an internal node for writing.
297 /// We don't need to return a raw ptr because we have unique access to the entire node.
298 fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
299 unsafe { &mut *(self.node.as_ptr() as *mut InternalNode<K, V>) }
303 impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
304 /// Finds the length of the node. This is the number of keys or values. In an
305 /// internal node, the number of edges is `len() + 1`.
306 /// For any node, the number of possible edge handles is also `len() + 1`.
307 /// Note that, despite being safe, calling this function can have the side effect
308 /// of invalidating mutable references that unsafe code has created.
309 pub fn len(&self) -> usize {
310 // Crucially, we only access the `len` field here. If BorrowType is marker::ValMut,
311 // there might be outstanding mutable references to values that we must not invalidate.
312 unsafe { (*self.as_leaf_ptr()).len as usize }
315 /// Returns the height of this node in the whole tree. Zero height denotes the
317 pub fn height(&self) -> usize {
321 /// Temporarily takes out another, immutable reference to the same node.
322 fn reborrow(&self) -> NodeRef<marker::Immut<'_>, K, V, Type> {
323 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
326 /// Exposes the leaf "portion" of any leaf or internal node.
327 /// If the node is a leaf, this function simply opens up its data.
328 /// If the node is an internal node, so not a leaf, it does have all the data a leaf has
329 /// (header, keys and values), and this function exposes that.
331 /// Returns a raw ptr to avoid invalidating other references to this node,
332 /// which is possible when BorrowType is marker::ValMut.
333 fn as_leaf_ptr(&self) -> *const LeafNode<K, V> {
334 // The node must be valid for at least the LeafNode portion.
335 // This is not a reference in the NodeRef type because we don't know if
336 // it should be unique or shared.
340 /// Borrows a reference to one of the keys stored in the node.
343 /// The node has more than `idx` initialized elements.
344 pub unsafe fn key_at(&self, idx: usize) -> &K {
345 unsafe { self.reborrow().into_key_at(idx) }
348 /// Borrows a reference to one of the values stored in the node.
351 /// The node has more than `idx` initialized elements.
352 unsafe fn val_at(&self, idx: usize) -> &V {
353 unsafe { self.reborrow().into_val_at(idx) }
356 /// Finds the parent of the current node. Returns `Ok(handle)` if the current
357 /// node actually has a parent, where `handle` points to the edge of the parent
358 /// that points to the current node. Returns `Err(self)` if the current node has
359 /// no parent, giving back the original `NodeRef`.
361 /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
362 /// both, upon success, do nothing.
365 ) -> Result<Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>, Self> {
366 // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut,
367 // there might be outstanding mutable references to values that we must not invalidate.
368 let parent_as_leaf = unsafe { (*self.as_leaf_ptr()).parent as *const LeafNode<K, V> };
369 if let Some(non_zero) = NonNull::new(parent_as_leaf as *mut _) {
371 node: NodeRef { height: self.height + 1, node: non_zero, _marker: PhantomData },
372 idx: unsafe { usize::from(*(*self.as_leaf_ptr()).parent_idx.as_ptr()) },
373 _marker: PhantomData,
380 pub fn first_edge(self) -> Handle<Self, marker::Edge> {
381 unsafe { Handle::new_edge(self, 0) }
384 pub fn last_edge(self) -> Handle<Self, marker::Edge> {
385 let len = self.len();
386 unsafe { Handle::new_edge(self, len) }
389 /// Note that `self` must be nonempty.
390 pub fn first_kv(self) -> Handle<Self, marker::KV> {
391 let len = self.len();
393 unsafe { Handle::new_kv(self, 0) }
396 /// Note that `self` must be nonempty.
397 pub fn last_kv(self) -> Handle<Self, marker::KV> {
398 let len = self.len();
400 unsafe { Handle::new_kv(self, len - 1) }
404 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
405 /// Exposes the data of a leaf node for reading in an immutable tree.
406 fn into_leaf(self) -> &'a LeafNode<K, V> {
407 // SAFETY: we can access the entire node freely and do no need raw pointers,
408 // because there can be no mutable references to this Immut tree.
409 unsafe { &(*self.as_leaf_ptr()) }
413 impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
414 /// Similar to `ascend`, gets a reference to a node's parent node, but also
415 /// deallocate the current node in the process. This is unsafe because the
416 /// current node will still be accessible despite being deallocated.
417 pub unsafe fn deallocate_and_ascend(
419 ) -> Option<Handle<NodeRef<marker::Owned, K, V, marker::Internal>, marker::Edge>> {
420 let height = self.height;
421 let node = self.node;
422 let ret = self.ascend().ok();
427 Layout::new::<InternalNode<K, V>>()
429 Layout::new::<LeafNode<K, V>>()
437 impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
438 /// Unsafely asserts to the compiler some static information about whether this
439 /// node is a `Leaf` or an `Internal`.
440 unsafe fn cast_unchecked<NewType>(self) -> NodeRef<marker::Mut<'a>, K, V, NewType> {
441 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
444 /// Temporarily takes out another, mutable reference to the same node. Beware, as
445 /// this method is very dangerous, doubly so since it may not immediately appear
448 /// Because mutable pointers can roam anywhere around the tree, the returned
449 /// pointer can easily be used to make the original pointer dangling, out of
450 /// bounds, or invalid under stacked borrow rules.
451 // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef`
452 // that restricts the use of navigation methods on reborrowed pointers,
453 // preventing this unsafety.
454 unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
455 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
458 /// Exposes the leaf "portion" of any leaf or internal node for writing.
459 /// If the node is a leaf, this function simply opens up its data.
460 /// If the node is an internal node, so not a leaf, it does have all the data a leaf has
461 /// (header, keys and values), and this function exposes that.
463 /// We don't need to return a raw ptr because we have unique access to the entire node.
464 fn as_leaf_mut(&mut self) -> &'a mut LeafNode<K, V> {
465 unsafe { &mut (*self.node.as_ptr()) }
468 fn keys_mut(&mut self) -> &mut [K] {
469 // SAFETY: the caller will not be able to call further methods on self
470 // until the key slice reference is dropped, as we have unique access
471 // for the lifetime of the borrow.
472 unsafe { self.reborrow_mut().into_key_slice_mut() }
475 fn vals_mut(&mut self) -> &mut [V] {
476 // SAFETY: the caller will not be able to call further methods on self
477 // until the value slice reference is dropped, as we have unique access
478 // for the lifetime of the borrow.
479 unsafe { self.reborrow_mut().into_val_slice_mut() }
483 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
485 /// The node has more than `idx` initialized elements.
486 unsafe fn into_key_at(self, idx: usize) -> &'a K {
487 unsafe { self.into_leaf().keys.get_unchecked(idx).assume_init_ref() }
491 /// The node has more than `idx` initialized elements.
492 unsafe fn into_val_at(self, idx: usize) -> &'a V {
493 unsafe { self.into_leaf().vals.get_unchecked(idx).assume_init_ref() }
497 impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
498 fn into_key_slice_mut(mut self) -> &'a mut [K] {
499 // SAFETY: The keys of a node must always be initialized up to length.
501 slice::from_raw_parts_mut(
502 MaybeUninit::slice_as_mut_ptr(&mut self.as_leaf_mut().keys),
508 fn into_val_slice_mut(mut self) -> &'a mut [V] {
509 // SAFETY: The values of a node must always be initialized up to length.
511 slice::from_raw_parts_mut(
512 MaybeUninit::slice_as_mut_ptr(&mut self.as_leaf_mut().vals),
519 /// The node has more than `idx` initialized elements.
520 unsafe fn into_key_mut_at(mut self, idx: usize) -> &'a mut K {
521 debug_assert!(idx < self.len());
523 let leaf = self.as_leaf_mut();
524 unsafe { leaf.keys.get_unchecked_mut(idx).assume_init_mut() }
528 /// The node has more than `idx` initialized elements.
529 unsafe fn into_val_mut_at(mut self, idx: usize) -> &'a mut V {
530 debug_assert!(idx < self.len());
532 let leaf = self.as_leaf_mut();
533 unsafe { leaf.vals.get_unchecked_mut(idx).assume_init_mut() }
537 impl<'a, K, V, Type> NodeRef<marker::ValMut<'a>, K, V, Type> {
539 /// The node has more than `idx` initialized elements.
540 unsafe fn into_key_val_mut_at(self, idx: usize) -> (&'a K, &'a mut V) {
541 // We only create a reference to the one element we are interested in,
542 // to avoid aliasing with outstanding references to other elements,
543 // in particular, those returned to the caller in earlier iterations.
544 let leaf = self.node.as_ptr();
545 // We must coerce to unsized array pointers because of Rust issue #74679.
546 let keys: *const [_] = unsafe { &raw const (*leaf).keys };
547 let vals: *mut [_] = unsafe { &raw mut (*leaf).vals };
548 // SAFETY: The keys and values of a node must always be initialized up to length.
549 let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() };
550 let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() };
555 impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
556 /// Adds a key/value pair to the end of the node.
557 pub fn push(&mut self, key: K, val: V) {
558 assert!(self.len() < CAPACITY);
560 let idx = self.len();
563 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
564 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
566 self.as_leaf_mut().len += 1;
569 /// Adds a key/value pair to the beginning of the node.
570 pub fn push_front(&mut self, key: K, val: V) {
571 assert!(self.len() < CAPACITY);
574 slice_insert(self.keys_mut(), 0, key);
575 slice_insert(self.vals_mut(), 0, val);
577 self.as_leaf_mut().len += 1;
581 impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
583 /// 'first' and 'after_last' must be in range.
584 unsafe fn correct_childrens_parent_links(&mut self, first: usize, after_last: usize) {
585 debug_assert!(first <= self.len());
586 debug_assert!(after_last <= self.len() + 1);
587 for i in first..after_last {
588 unsafe { Handle::new_edge(self.reborrow_mut(), i) }.correct_parent_link();
592 fn correct_all_childrens_parent_links(&mut self) {
593 let len = self.len();
594 unsafe { self.correct_childrens_parent_links(0, len + 1) };
598 impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
599 /// Adds a key/value pair and an edge to go to the right of that pair to
600 /// the end of the node.
601 pub fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
602 assert!(edge.height == self.height - 1);
603 assert!(self.len() < CAPACITY);
605 let idx = self.len();
608 ptr::write(self.keys_mut().get_unchecked_mut(idx), key);
609 ptr::write(self.vals_mut().get_unchecked_mut(idx), val);
610 self.as_internal_mut().edges.get_unchecked_mut(idx + 1).write(edge.node);
612 self.as_leaf_mut().len += 1;
614 Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
618 /// Adds a key/value pair and an edge to go to the left of that pair to
619 /// the beginning of the node.
620 pub fn push_front(&mut self, key: K, val: V, edge: Root<K, V>) {
621 assert!(edge.height == self.height - 1);
622 assert!(self.len() < CAPACITY);
625 slice_insert(self.keys_mut(), 0, key);
626 slice_insert(self.vals_mut(), 0, val);
628 slice::from_raw_parts_mut(
629 MaybeUninit::slice_as_mut_ptr(&mut self.as_internal_mut().edges),
637 self.as_leaf_mut().len += 1;
639 self.correct_all_childrens_parent_links();
643 impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
644 /// Removes a key/value pair from the end of this node and returns the pair.
645 /// If this is an internal node, also removes the edge that was to the right
646 /// of that pair and returns the orphaned node that this edge owned with its
648 pub fn pop(&mut self) -> (K, V, Option<Root<K, V>>) {
649 assert!(self.len() > 0);
651 let idx = self.len() - 1;
654 let key = ptr::read(self.key_at(idx));
655 let val = ptr::read(self.val_at(idx));
656 let edge = match self.reborrow_mut().force() {
657 ForceResult::Leaf(_) => None,
658 ForceResult::Internal(mut internal) => {
660 ptr::read(internal.as_internal().edges.get_unchecked(idx + 1).as_ptr());
661 let mut new_root = Root { node: edge, height: internal.height - 1 };
662 new_root.node_as_mut().as_leaf_mut().parent = ptr::null();
667 self.as_leaf_mut().len -= 1;
672 /// Removes a key/value pair from the beginning of this node. If this is an internal node,
673 /// also removes the edge that was to the left of that pair.
674 pub fn pop_front(&mut self) -> (K, V, Option<Root<K, V>>) {
675 assert!(self.len() > 0);
677 let old_len = self.len();
680 let key = slice_remove(self.keys_mut(), 0);
681 let val = slice_remove(self.vals_mut(), 0);
682 let edge = match self.reborrow_mut().force() {
683 ForceResult::Leaf(_) => None,
684 ForceResult::Internal(mut internal) => {
685 let edge = slice_remove(
686 slice::from_raw_parts_mut(
687 MaybeUninit::slice_as_mut_ptr(&mut internal.as_internal_mut().edges),
693 let mut new_root = Root { node: edge, height: internal.height - 1 };
694 new_root.node_as_mut().as_leaf_mut().parent = ptr::null();
696 for i in 0..old_len {
697 Handle::new_edge(internal.reborrow_mut(), i).correct_parent_link();
704 self.as_leaf_mut().len -= 1;
710 fn into_kv_pointers_mut(mut self) -> (*mut K, *mut V) {
711 (self.keys_mut().as_mut_ptr(), self.vals_mut().as_mut_ptr())
715 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
716 /// Checks whether a node is an `Internal` node or a `Leaf` node.
720 NodeRef<BorrowType, K, V, marker::Leaf>,
721 NodeRef<BorrowType, K, V, marker::Internal>,
723 if self.height == 0 {
724 ForceResult::Leaf(NodeRef {
727 _marker: PhantomData,
730 ForceResult::Internal(NodeRef {
733 _marker: PhantomData,
739 /// A reference to a specific key/value pair or edge within a node. The `Node` parameter
740 /// must be a `NodeRef`, while the `Type` can either be `KV` (signifying a handle on a key/value
741 /// pair) or `Edge` (signifying a handle on an edge).
743 /// Note that even `Leaf` nodes can have `Edge` handles. Instead of representing a pointer to
744 /// a child node, these represent the spaces where child pointers would go between the key/value
745 /// pairs. For example, in a node with length 2, there would be 3 possible edge locations - one
746 /// to the left of the node, one between the two pairs, and one at the right of the node.
747 pub struct Handle<Node, Type> {
750 _marker: PhantomData<Type>,
753 impl<Node: Copy, Type> Copy for Handle<Node, Type> {}
754 // We don't need the full generality of `#[derive(Clone)]`, as the only time `Node` will be
755 // `Clone`able is when it is an immutable reference and therefore `Copy`.
756 impl<Node: Copy, Type> Clone for Handle<Node, Type> {
757 fn clone(&self) -> Self {
762 impl<Node, Type> Handle<Node, Type> {
763 /// Retrieves the node that contains the edge or key/value pair this handle points to.
764 pub fn into_node(self) -> Node {
768 /// Returns the position of this handle in the node.
769 pub fn idx(&self) -> usize {
774 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
775 /// Creates a new handle to a key/value pair in `node`.
776 /// Unsafe because the caller must ensure that `idx < node.len()`.
777 pub unsafe fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
778 debug_assert!(idx < node.len());
780 Handle { node, idx, _marker: PhantomData }
783 pub fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
784 unsafe { Handle::new_edge(self.node, self.idx) }
787 pub fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
788 unsafe { Handle::new_edge(self.node, self.idx + 1) }
792 impl<BorrowType, K, V, NodeType, HandleType> PartialEq
793 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
795 fn eq(&self, other: &Self) -> bool {
796 self.node.node == other.node.node && self.idx == other.idx
800 impl<BorrowType, K, V, NodeType, HandleType> PartialOrd
801 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
803 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
804 if self.node.node == other.node.node { Some(self.idx.cmp(&other.idx)) } else { None }
808 impl<BorrowType, K, V, NodeType, HandleType>
809 Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
811 /// Temporarily takes out another, immutable handle on the same location.
812 pub fn reborrow(&self) -> Handle<NodeRef<marker::Immut<'_>, K, V, NodeType>, HandleType> {
813 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
814 Handle { node: self.node.reborrow(), idx: self.idx, _marker: PhantomData }
818 impl<'a, K, V, NodeType, HandleType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
819 /// Temporarily takes out another, mutable handle on the same location. Beware, as
820 /// this method is very dangerous, doubly so since it may not immediately appear
823 /// For details, see `NodeRef::reborrow_mut`.
824 pub unsafe fn reborrow_mut(
826 ) -> Handle<NodeRef<marker::Mut<'_>, K, V, NodeType>, HandleType> {
827 // We can't use Handle::new_kv or Handle::new_edge because we don't know our type
828 Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData }
832 impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
833 /// Creates a new handle to an edge in `node`.
834 /// Unsafe because the caller must ensure that `idx <= node.len()`.
835 pub unsafe fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
836 debug_assert!(idx <= node.len());
838 Handle { node, idx, _marker: PhantomData }
841 pub fn left_kv(self) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
843 Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) })
849 pub fn right_kv(self) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
850 if self.idx < self.node.len() {
851 Ok(unsafe { Handle::new_kv(self.node, self.idx) })
858 enum InsertionPlace {
863 /// Given an edge index where we want to insert into a node filled to capacity,
864 /// computes a sensible KV index of a split point and where to perform the insertion.
865 /// The goal of the split point is for its key and value to end up in a parent node;
866 /// the keys, values and edges to the left of the split point become the left child;
867 /// the keys, values and edges to the right of the split point become the right child.
868 fn splitpoint(edge_idx: usize) -> (usize, InsertionPlace) {
869 debug_assert!(edge_idx <= CAPACITY);
870 // Rust issue #74834 tries to explain these symmetric rules.
872 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, InsertionPlace::Left(edge_idx)),
873 EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, InsertionPlace::Left(edge_idx)),
874 EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, InsertionPlace::Right(0)),
875 _ => (KV_IDX_CENTER + 1, InsertionPlace::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))),
879 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::Edge> {
880 /// Helps implementations of `insert_fit` for a particular `NodeType`,
881 /// by taking care of leaf data.
882 /// Inserts a new key/value pair between the key/value pairs to the right and left of
883 /// this edge. This method assumes that there is enough space in the node for the new
885 fn leafy_insert_fit(&mut self, key: K, val: V) {
886 // Necessary for correctness, but in a private module
887 debug_assert!(self.node.len() < CAPACITY);
890 slice_insert(self.node.keys_mut(), self.idx, key);
891 slice_insert(self.node.vals_mut(), self.idx, val);
893 self.node.as_leaf_mut().len += 1;
898 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
899 /// Inserts a new key/value pair between the key/value pairs to the right and left of
900 /// this edge. This method assumes that there is enough space in the node for the new
903 /// The returned pointer points to the inserted value.
904 fn insert_fit(&mut self, key: K, val: V) -> *mut V {
905 self.leafy_insert_fit(key, val);
906 unsafe { self.node.vals_mut().get_unchecked_mut(self.idx) }
910 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
911 /// Inserts a new key/value pair between the key/value pairs to the right and left of
912 /// this edge. This method splits the node if there isn't enough room.
914 /// The returned pointer points to the inserted value.
915 fn insert(mut self, key: K, val: V) -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) {
916 if self.node.len() < CAPACITY {
917 let ptr = self.insert_fit(key, val);
918 let kv = unsafe { Handle::new_kv(self.node, self.idx) };
919 (InsertResult::Fit(kv), ptr)
921 let (middle_kv_idx, insertion) = splitpoint(self.idx);
922 let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
923 let (mut left, k, v, mut right) = middle.split();
924 let ptr = match insertion {
925 InsertionPlace::Left(insert_idx) => unsafe {
926 Handle::new_edge(left.reborrow_mut(), insert_idx).insert_fit(key, val)
928 InsertionPlace::Right(insert_idx) => unsafe {
930 right.node_as_mut().cast_unchecked::<marker::Leaf>(),
933 .insert_fit(key, val)
936 (InsertResult::Split(SplitResult { left: left.forget_type(), k, v, right }), ptr)
941 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
942 /// Fixes the parent pointer and index in the child node below this edge. This is useful
943 /// when the ordering of edges has been changed, such as in the various `insert` methods.
944 fn correct_parent_link(mut self) {
945 let idx = self.idx as u16;
946 let ptr = self.node.as_internal_mut() as *mut _;
947 let mut child = self.descend();
948 child.as_leaf_mut().parent = ptr;
949 child.as_leaf_mut().parent_idx.write(idx);
953 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
954 /// Inserts a new key/value pair and an edge that will go to the right of that new pair
955 /// between this edge and the key/value pair to the right of this edge. This method assumes
956 /// that there is enough space in the node for the new pair to fit.
957 fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
958 // Necessary for correctness, but in an internal module
959 debug_assert!(self.node.len() < CAPACITY);
960 debug_assert!(edge.height == self.node.height - 1);
963 self.leafy_insert_fit(key, val);
966 slice::from_raw_parts_mut(
967 MaybeUninit::slice_as_mut_ptr(&mut self.node.as_internal_mut().edges),
974 for i in (self.idx + 1)..(self.node.len() + 1) {
975 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
980 /// Inserts a new key/value pair and an edge that will go to the right of that new pair
981 /// between this edge and the key/value pair to the right of this edge. This method splits
982 /// the node if there isn't enough room.
988 ) -> InsertResult<'a, K, V, marker::Internal> {
989 assert!(edge.height == self.node.height - 1);
991 if self.node.len() < CAPACITY {
992 self.insert_fit(key, val, edge);
993 let kv = unsafe { Handle::new_kv(self.node, self.idx) };
994 InsertResult::Fit(kv)
996 let (middle_kv_idx, insertion) = splitpoint(self.idx);
997 let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
998 let (mut left, k, v, mut right) = middle.split();
1000 InsertionPlace::Left(insert_idx) => unsafe {
1001 Handle::new_edge(left.reborrow_mut(), insert_idx).insert_fit(key, val, edge);
1003 InsertionPlace::Right(insert_idx) => unsafe {
1005 right.node_as_mut().cast_unchecked::<marker::Internal>(),
1008 .insert_fit(key, val, edge);
1011 InsertResult::Split(SplitResult { left: left.forget_type(), k, v, right })
1016 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
1017 /// Inserts a new key/value pair between the key/value pairs to the right and left of
1018 /// this edge. This method splits the node if there isn't enough room, and tries to
1019 /// insert the split off portion into the parent node recursively, until the root is reached.
1021 /// If the returned result is a `Fit`, its handle's node can be this edge's node or an ancestor.
1022 /// If the returned result is a `Split`, the `left` field will be the root node.
1023 /// The returned pointer points to the inserted value.
1024 pub fn insert_recursing(
1028 ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) {
1029 let (mut split, val_ptr) = match self.insert(key, value) {
1030 (InsertResult::Fit(handle), ptr) => {
1031 return (InsertResult::Fit(handle.forget_node_type()), ptr);
1033 (InsertResult::Split(split), val_ptr) => (split, val_ptr),
1037 split = match split.left.ascend() {
1038 Ok(parent) => match parent.insert(split.k, split.v, split.right) {
1039 InsertResult::Fit(handle) => {
1040 return (InsertResult::Fit(handle.forget_node_type()), val_ptr);
1042 InsertResult::Split(split) => split,
1045 return (InsertResult::Split(SplitResult { left: root, ..split }), val_ptr);
1052 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1053 /// Finds the node pointed to by this edge.
1055 /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
1056 /// both, upon success, do nothing.
1057 pub fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1058 // We need to use raw pointers to nodes because, if BorrowType is
1059 // marker::ValMut, there might be outstanding mutable references to
1060 // values that we must not invalidate. There's no worry accessing the
1061 // height field because that value is copied. Beware that, once the
1062 // node pointer is dereferenced, we access the edges array with a
1063 // reference (Rust issue #73987) and invalidate any other references
1064 // to or inside the array, should any be around.
1065 let internal_node = self.node.as_internal_ptr();
1067 height: self.node.height - 1,
1068 node: unsafe { (&*(*internal_node).edges.get_unchecked(self.idx).as_ptr()).as_ptr() },
1069 _marker: PhantomData,
1074 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
1075 pub fn into_kv(self) -> (&'a K, &'a V) {
1076 (unsafe { self.node.into_key_at(self.idx) }, unsafe { self.node.into_val_at(self.idx) })
1080 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1081 pub fn into_key_mut(self) -> &'a mut K {
1082 unsafe { self.node.into_key_mut_at(self.idx) }
1085 pub fn into_val_mut(self) -> &'a mut V {
1086 unsafe { self.node.into_val_mut_at(self.idx) }
1090 impl<'a, K, V, NodeType> Handle<NodeRef<marker::ValMut<'a>, K, V, NodeType>, marker::KV> {
1091 pub fn into_kv_valmut(self) -> (&'a K, &'a mut V) {
1092 unsafe { self.node.into_key_val_mut_at(self.idx) }
1096 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1097 pub fn kv_mut(&mut self) -> (&mut K, &mut V) {
1098 // We cannot call into_key_mut_at and into_val_mut_at, because calling the second one
1099 // invalidates the reference returned by the first.
1100 let leaf = self.node.as_leaf_mut();
1101 let key = unsafe { leaf.keys.get_unchecked_mut(self.idx).assume_init_mut() };
1102 let val = unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() };
1107 impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1108 /// Helps implementations of `split` for a particular `NodeType`,
1109 /// by taking care of leaf data.
1110 fn leafy_split(&mut self, new_node: &mut LeafNode<K, V>) -> (K, V, usize) {
1112 let k = ptr::read(self.node.key_at(self.idx));
1113 let v = ptr::read(self.node.val_at(self.idx));
1115 let new_len = self.node.len() - self.idx - 1;
1117 ptr::copy_nonoverlapping(
1118 self.node.key_at(self.idx + 1),
1119 new_node.keys.as_mut_ptr() as *mut K,
1122 ptr::copy_nonoverlapping(
1123 self.node.val_at(self.idx + 1),
1124 new_node.vals.as_mut_ptr() as *mut V,
1128 self.node.as_leaf_mut().len = self.idx as u16;
1129 new_node.len = new_len as u16;
1135 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1136 /// Splits the underlying node into three parts:
1138 /// - The node is truncated to only contain the key/value pairs to the right of
1140 /// - The key and value pointed to by this handle and extracted.
1141 /// - All the key/value pairs to the right of this handle are put into a newly
1143 pub fn split(mut self) -> (NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, K, V, Root<K, V>) {
1145 let mut new_node = Box::new(LeafNode::new());
1147 let (k, v, _) = self.leafy_split(&mut new_node);
1149 (self.node, k, v, Root { node: BoxedNode::from_leaf(new_node), height: 0 })
1153 /// Removes the key/value pair pointed to by this handle and returns it, along with the edge
1154 /// that the key/value pair collapsed into.
1157 ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
1159 let k = slice_remove(self.node.keys_mut(), self.idx);
1160 let v = slice_remove(self.node.vals_mut(), self.idx);
1161 self.node.as_leaf_mut().len -= 1;
1162 ((k, v), self.left_edge())
1167 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1168 /// Returns `true` if it is valid to call `.merge()`, i.e., whether there is enough room in
1169 /// a node to hold the combination of the nodes to the left and right of this handle along
1170 /// with the key/value pair at this handle.
1171 pub fn can_merge(&self) -> bool {
1172 (self.reborrow().left_edge().descend().len()
1173 + self.reborrow().right_edge().descend().len()
1179 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1180 /// Splits the underlying node into three parts:
1182 /// - The node is truncated to only contain the edges and key/value pairs to the
1183 /// right of this handle.
1184 /// - The key and value pointed to by this handle and extracted.
1185 /// - All the edges and key/value pairs to the right of this handle are put into
1186 /// a newly allocated node.
1187 pub fn split(mut self) -> (NodeRef<marker::Mut<'a>, K, V, marker::Internal>, K, V, Root<K, V>) {
1189 let mut new_node = Box::new(InternalNode::new());
1191 let (k, v, new_len) = self.leafy_split(&mut new_node.data);
1192 let height = self.node.height;
1193 let old_node = &*self.node.as_internal_ptr();
1195 ptr::copy_nonoverlapping(
1196 old_node.edges.as_ptr().add(self.idx + 1),
1197 new_node.edges.as_mut_ptr(),
1201 let mut new_root = Root { node: BoxedNode::from_internal(new_node), height };
1203 for i in 0..(new_len + 1) {
1204 Handle::new_edge(new_root.node_as_mut().cast_unchecked(), i).correct_parent_link();
1207 (self.node, k, v, new_root)
1211 /// Combines the node immediately to the left of this handle, the key/value pair pointed
1212 /// to by this handle, and the node immediately to the right of this handle into one new
1213 /// child of the underlying node, returning an edge referencing that new child.
1215 /// Panics unless this edge `.can_merge()`.
1218 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1219 let self1 = unsafe { ptr::read(&self) };
1220 let self2 = unsafe { ptr::read(&self) };
1221 let mut left_node = self1.left_edge().descend();
1222 let left_len = left_node.len();
1223 let right_node = self2.right_edge().descend();
1224 let right_len = right_node.len();
1226 assert!(left_len + right_len < CAPACITY);
1230 left_node.keys_mut().get_unchecked_mut(left_len),
1231 slice_remove(self.node.keys_mut(), self.idx),
1233 ptr::copy_nonoverlapping(
1234 right_node.key_at(0),
1235 left_node.keys_mut().as_mut_ptr().add(left_len + 1),
1239 left_node.vals_mut().get_unchecked_mut(left_len),
1240 slice_remove(self.node.vals_mut(), self.idx),
1242 ptr::copy_nonoverlapping(
1243 right_node.val_at(0),
1244 left_node.vals_mut().as_mut_ptr().add(left_len + 1),
1248 slice_remove(&mut self.node.as_internal_mut().edges, self.idx + 1);
1249 for i in self.idx + 1..self.node.len() {
1250 Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link();
1252 self.node.as_leaf_mut().len -= 1;
1254 left_node.as_leaf_mut().len += right_len as u16 + 1;
1256 if self.node.height > 1 {
1257 // SAFETY: the height of the nodes being merged is one below the height
1258 // of the node of this edge, thus above zero, so they are internal.
1259 let mut left_node = left_node.cast_unchecked();
1260 let mut right_node = right_node.cast_unchecked();
1261 ptr::copy_nonoverlapping(
1262 right_node.as_internal().edges.as_ptr(),
1263 left_node.as_internal_mut().edges.as_mut_ptr().add(left_len + 1),
1267 for i in left_len + 1..left_len + right_len + 2 {
1268 Handle::new_edge(left_node.reborrow_mut(), i).correct_parent_link();
1271 Global.dealloc(right_node.node.cast(), Layout::new::<InternalNode<K, V>>());
1273 Global.dealloc(right_node.node.cast(), Layout::new::<LeafNode<K, V>>());
1276 Handle::new_edge(self.node, self.idx)
1280 /// This removes a key/value pair from the left child and places it in the key/value storage
1281 /// pointed to by this handle while pushing the old key/value pair of this handle into the right
1283 pub fn steal_left(&mut self) {
1285 let (k, v, edge) = self.reborrow_mut().left_edge().descend().pop();
1287 let k = mem::replace(self.kv_mut().0, k);
1288 let v = mem::replace(self.kv_mut().1, v);
1290 match self.reborrow_mut().right_edge().descend().force() {
1291 ForceResult::Leaf(mut leaf) => leaf.push_front(k, v),
1292 ForceResult::Internal(mut internal) => internal.push_front(k, v, edge.unwrap()),
1297 /// This removes a key/value pair from the right child and places it in the key/value storage
1298 /// pointed to by this handle while pushing the old key/value pair of this handle into the left
1300 pub fn steal_right(&mut self) {
1302 let (k, v, edge) = self.reborrow_mut().right_edge().descend().pop_front();
1304 let k = mem::replace(self.kv_mut().0, k);
1305 let v = mem::replace(self.kv_mut().1, v);
1307 match self.reborrow_mut().left_edge().descend().force() {
1308 ForceResult::Leaf(mut leaf) => leaf.push(k, v),
1309 ForceResult::Internal(mut internal) => internal.push(k, v, edge.unwrap()),
1314 /// This does stealing similar to `steal_left` but steals multiple elements at once.
1315 pub fn bulk_steal_left(&mut self, count: usize) {
1317 let mut left_node = ptr::read(self).left_edge().descend();
1318 let left_len = left_node.len();
1319 let mut right_node = ptr::read(self).right_edge().descend();
1320 let right_len = right_node.len();
1322 // Make sure that we may steal safely.
1323 assert!(right_len + count <= CAPACITY);
1324 assert!(left_len >= count);
1326 let new_left_len = left_len - count;
1330 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1331 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1333 let kv = self.kv_mut();
1334 (kv.0 as *mut K, kv.1 as *mut V)
1337 // Make room for stolen elements in the right child.
1338 ptr::copy(right_kv.0, right_kv.0.add(count), right_len);
1339 ptr::copy(right_kv.1, right_kv.1.add(count), right_len);
1341 // Move elements from the left child to the right one.
1342 move_kv(left_kv, new_left_len + 1, right_kv, 0, count - 1);
1344 // Move parent's key/value pair to the right child.
1345 move_kv(parent_kv, 0, right_kv, count - 1, 1);
1347 // Move the left-most stolen pair to the parent.
1348 move_kv(left_kv, new_left_len, parent_kv, 0, 1);
1351 left_node.as_leaf_mut().len -= count as u16;
1352 right_node.as_leaf_mut().len += count as u16;
1354 match (left_node.force(), right_node.force()) {
1355 (ForceResult::Internal(left), ForceResult::Internal(mut right)) => {
1356 // Make room for stolen edges.
1357 let right_edges = right.reborrow_mut().as_internal_mut().edges.as_mut_ptr();
1358 ptr::copy(right_edges, right_edges.add(count), right_len + 1);
1359 right.correct_childrens_parent_links(count, count + right_len + 1);
1361 move_edges(left, new_left_len + 1, right, 0, count);
1363 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1371 /// The symmetric clone of `bulk_steal_left`.
1372 pub fn bulk_steal_right(&mut self, count: usize) {
1374 let mut left_node = ptr::read(self).left_edge().descend();
1375 let left_len = left_node.len();
1376 let mut right_node = ptr::read(self).right_edge().descend();
1377 let right_len = right_node.len();
1379 // Make sure that we may steal safely.
1380 assert!(left_len + count <= CAPACITY);
1381 assert!(right_len >= count);
1383 let new_right_len = right_len - count;
1387 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1388 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1390 let kv = self.kv_mut();
1391 (kv.0 as *mut K, kv.1 as *mut V)
1394 // Move parent's key/value pair to the left child.
1395 move_kv(parent_kv, 0, left_kv, left_len, 1);
1397 // Move elements from the right child to the left one.
1398 move_kv(right_kv, 0, left_kv, left_len + 1, count - 1);
1400 // Move the right-most stolen pair to the parent.
1401 move_kv(right_kv, count - 1, parent_kv, 0, 1);
1403 // Fix right indexing
1404 ptr::copy(right_kv.0.add(count), right_kv.0, new_right_len);
1405 ptr::copy(right_kv.1.add(count), right_kv.1, new_right_len);
1408 left_node.as_leaf_mut().len += count as u16;
1409 right_node.as_leaf_mut().len -= count as u16;
1411 match (left_node.force(), right_node.force()) {
1412 (ForceResult::Internal(left), ForceResult::Internal(mut right)) => {
1413 move_edges(right.reborrow_mut(), 0, left, left_len + 1, count);
1415 // Fix right indexing.
1416 let right_edges = right.reborrow_mut().as_internal_mut().edges.as_mut_ptr();
1417 ptr::copy(right_edges.add(count), right_edges, new_right_len + 1);
1418 right.correct_childrens_parent_links(0, new_right_len + 1);
1420 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1429 unsafe fn move_kv<K, V>(
1430 source: (*mut K, *mut V),
1431 source_offset: usize,
1432 dest: (*mut K, *mut V),
1437 ptr::copy_nonoverlapping(source.0.add(source_offset), dest.0.add(dest_offset), count);
1438 ptr::copy_nonoverlapping(source.1.add(source_offset), dest.1.add(dest_offset), count);
1442 // Source and destination must have the same height.
1443 unsafe fn move_edges<K, V>(
1444 mut source: NodeRef<marker::Mut<'_>, K, V, marker::Internal>,
1445 source_offset: usize,
1446 mut dest: NodeRef<marker::Mut<'_>, K, V, marker::Internal>,
1450 let source_ptr = source.as_internal().edges.as_ptr();
1451 let dest_ptr = dest.as_internal_mut().edges.as_mut_ptr();
1453 ptr::copy_nonoverlapping(source_ptr.add(source_offset), dest_ptr.add(dest_offset), count);
1454 dest.correct_childrens_parent_links(dest_offset, dest_offset + count);
1458 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Leaf> {
1459 /// Removes any static information asserting that this node is a `Leaf` node.
1460 pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1461 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
1465 impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
1466 /// Removes any static information asserting that this node is an `Internal` node.
1467 pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1468 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
1472 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1473 pub fn forget_node_type(
1475 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1476 unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1480 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1481 pub fn forget_node_type(
1483 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1484 unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1488 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::KV> {
1489 pub fn forget_node_type(
1491 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1492 unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1496 impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::KV> {
1497 pub fn forget_node_type(
1499 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1500 unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1504 impl<BorrowType, K, V, HandleType>
1505 Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, HandleType>
1507 /// Checks whether the underlying node is an `Internal` node or a `Leaf` node.
1511 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, HandleType>,
1512 Handle<NodeRef<BorrowType, K, V, marker::Internal>, HandleType>,
1514 match self.node.force() {
1515 ForceResult::Leaf(node) => {
1516 ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData })
1518 ForceResult::Internal(node) => {
1519 ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData })
1525 impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1526 /// Move the suffix after `self` from one node to another one. `right` must be empty.
1527 /// The first edge of `right` remains unchanged.
1530 right: &mut NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1533 let left_new_len = self.idx;
1534 let mut left_node = self.reborrow_mut().into_node();
1536 let right_new_len = left_node.len() - left_new_len;
1537 let mut right_node = right.reborrow_mut();
1539 assert!(right_node.len() == 0);
1540 assert!(left_node.height == right_node.height);
1542 if right_new_len > 0 {
1543 let left_kv = left_node.reborrow_mut().into_kv_pointers_mut();
1544 let right_kv = right_node.reborrow_mut().into_kv_pointers_mut();
1546 move_kv(left_kv, left_new_len, right_kv, 0, right_new_len);
1548 left_node.as_leaf_mut().len = left_new_len as u16;
1549 right_node.as_leaf_mut().len = right_new_len as u16;
1551 match (left_node.force(), right_node.force()) {
1552 (ForceResult::Internal(left), ForceResult::Internal(right)) => {
1553 move_edges(left, left_new_len + 1, right, 1, right_new_len);
1555 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1565 pub enum ForceResult<Leaf, Internal> {
1570 /// Result of insertion, when a node needed to expand beyond its capacity.
1571 /// Does not distinguish between `Leaf` and `Internal` because `Root` doesn't.
1572 pub struct SplitResult<'a, K, V> {
1573 // Altered node in existing tree with elements and edges that belong to the left of `k`.
1574 pub left: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1575 // Some key and value split off, to be inserted elsewhere.
1578 // Owned, unattached, new node with elements and edges that belong to the right of `k`.
1579 pub right: Root<K, V>,
1582 pub enum InsertResult<'a, K, V, Type> {
1583 Fit(Handle<NodeRef<marker::Mut<'a>, K, V, Type>, marker::KV>),
1584 Split(SplitResult<'a, K, V>),
1588 use core::marker::PhantomData;
1591 pub enum Internal {}
1592 pub enum LeafOrInternal {}
1595 pub struct Immut<'a>(PhantomData<&'a ()>);
1596 pub struct Mut<'a>(PhantomData<&'a mut ()>);
1597 pub struct ValMut<'a>(PhantomData<&'a mut ()>);
1603 unsafe fn slice_insert<T>(slice: &mut [T], idx: usize, val: T) {
1605 ptr::copy(slice.as_ptr().add(idx), slice.as_mut_ptr().add(idx + 1), slice.len() - idx);
1606 ptr::write(slice.get_unchecked_mut(idx), val);
1610 unsafe fn slice_remove<T>(slice: &mut [T], idx: usize) -> T {
1612 let ret = ptr::read(slice.get_unchecked(idx));
1613 ptr::copy(slice.as_ptr().add(idx + 1), slice.as_mut_ptr().add(idx), slice.len() - idx - 1);