Debian Codegraph @

debian/missing-sources/fallible_collections/src/btree/node.rs

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