1use core::marker::PhantomData;
35use core::mem::{self, MaybeUninit};
36use core::num::NonZero;
37use core::ptr::{self, NonNull};
38use core::slice::SliceIndex;
39
40use crate::alloc::{Allocator, AllocatorClone, Layout};
41use crate::boxed::Box;
42
43const B: usize = 6;
44pub(super) const CAPACITY: usize = 2 * B - 1;
45pub(super) const MIN_LEN_AFTER_SPLIT: usize = B - 1;
46const KV_IDX_CENTER: usize = B - 1;
47const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1;
48const EDGE_IDX_RIGHT_OF_CENTER: usize = B;
49
50struct LeafNode<K, V> {
52 parent: Option<NonNull<InternalNode<K, V>>>,
54
55 parent_idx: MaybeUninit<u16>,
59
60 len: u16,
62
63 keys: [MaybeUninit<K>; CAPACITY],
66 vals: [MaybeUninit<V>; CAPACITY],
67}
68
69impl<K, V> LeafNode<K, V> {
70 unsafe fn init(this: *mut Self) {
76 unsafe {
80 (&raw mut (*this).parent).write(None);
82 (&raw mut (*this).len).write(0);
83 }
84 }
85
86 fn new<A: AllocatorClone>(alloc: A) -> Box<Self, A> {
88 let mut leaf = Box::new_uninit_in(alloc);
89
90 unsafe { LeafNode::init(leaf.as_mut_ptr()) };
92 unsafe { leaf.assume_init() }
94 }
95}
96
97#[repr(C)]
103struct InternalNode<K, V> {
105 data: LeafNode<K, V>,
106
107 edges: [MaybeUninit<BoxedNode<K, V>>; 2 * B],
111}
112
113impl<K, V> InternalNode<K, V> {
114 unsafe fn new<A: AllocatorClone>(alloc: A) -> Box<Self, A> {
121 let mut node = Box::<Self, _>::new_uninit_in(alloc);
122
123 unsafe { LeafNode::init(&raw mut (*node.as_mut_ptr()).data) };
125 unsafe { node.assume_init() }
127 }
128}
129
130type BoxedNode<K, V> = NonNull<LeafNode<K, V>>;
137
138pub(super) struct NodeRef<BorrowType, K, V, Type> {
190 height: usize,
196 node: NonNull<LeafNode<K, V>>,
199 _marker: PhantomData<(BorrowType, Type)>,
200}
201
202pub(super) type Root<K, V> = NodeRef<marker::Owned, K, V, marker::LeafOrInternal>;
206
207impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef<marker::Immut<'a>, K, V, Type> {}
208impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef<marker::Immut<'a>, K, V, Type> {
209 fn clone(&self) -> Self {
210 *self
211 }
212}
213
214unsafe impl<BorrowType, K: Sync, V: Sync, Type> Sync for NodeRef<BorrowType, K, V, Type> {}
215
216unsafe impl<K: Sync, V: Sync, Type> Send for NodeRef<marker::Immut<'_>, K, V, Type> {}
217unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Mut<'_>, K, V, Type> {}
218unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::ValMut<'_>, K, V, Type> {}
219unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Owned, K, V, Type> {}
220unsafe impl<K: Send, V: Send, Type> Send for NodeRef<marker::Dying, K, V, Type> {}
221
222impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
223 pub(super) fn new_leaf<A: AllocatorClone>(alloc: A) -> Self {
224 Self::from_new_leaf(LeafNode::new(alloc))
225 }
226
227 fn from_new_leaf<A: AllocatorClone>(leaf: Box<LeafNode<K, V>, A>) -> Self {
228 let (node, _alloc) = Box::into_non_null_with_allocator(leaf);
230 NodeRef { height: 0, node, _marker: PhantomData }
231 }
232}
233
234impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
235 fn new_internal<A: AllocatorClone>(child: Root<K, V>, alloc: A) -> Self {
237 let mut new_node = unsafe { InternalNode::new(alloc) };
239 new_node.edges[0].write(child.node);
240 NodeRef::from_new_internal(new_node, NonZero::new(child.height + 1).unwrap())
241 }
242
243 fn from_new_internal<A: AllocatorClone>(
245 internal: Box<InternalNode<K, V>, A>,
246 height: NonZero<usize>,
247 ) -> Self {
248 let (node, _alloc) = Box::into_non_null_with_allocator(internal);
250 let mut this = NodeRef { height: height.into(), node: node.cast(), _marker: PhantomData };
251 this.borrow_mut().correct_all_childrens_parent_links();
252 this
253 }
254}
255
256impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
257 fn from_internal(node: NonNull<InternalNode<K, V>>, height: usize) -> Self {
259 if true {
if !(height > 0) {
::core::panicking::panic("assertion failed: height > 0")
};
};debug_assert!(height > 0);
260 NodeRef { height, node: node.cast(), _marker: PhantomData }
261 }
262}
263
264impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
265 fn as_internal_ptr(this: &Self) -> *mut InternalNode<K, V> {
269 this.node.as_ptr() as *mut InternalNode<K, V>
271 }
272}
273
274impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
275 fn as_internal_mut(&mut self) -> &mut InternalNode<K, V> {
277 let ptr = Self::as_internal_ptr(self);
278 unsafe { &mut *ptr }
280 }
281}
282
283impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
284 pub(super) fn len(&self) -> usize {
289 unsafe { usize::from((*Self::as_leaf_ptr(self)).len) }
292 }
293
294 pub(super) fn height(&self) -> usize {
300 self.height
301 }
302
303 pub(super) fn reborrow(&self) -> NodeRef<marker::Immut<'_>, K, V, Type> {
305 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
306 }
307
308 fn as_leaf_ptr(this: &Self) -> *mut LeafNode<K, V> {
312 this.node.as_ptr()
316 }
317}
318
319impl<BorrowType: marker::BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
320 pub(super) fn ascend(
330 self,
331 ) -> Result<Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>, Self> {
332 const {
333 if !BorrowType::TRAVERSAL_PERMIT {
::core::panicking::panic("assertion failed: BorrowType::TRAVERSAL_PERMIT")
};assert!(BorrowType::TRAVERSAL_PERMIT);
334 }
335
336 let leaf_ptr: *const _ = Self::as_leaf_ptr(&self);
339 unsafe { (*leaf_ptr).parent }
341 .as_ref()
342 .map(|parent| Handle {
343 node: NodeRef::from_internal(*parent, self.height + 1),
344 idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) },
346 _marker: PhantomData,
347 })
348 .ok_or(self)
349 }
350
351 pub(super) fn first_edge(self) -> Handle<Self, marker::Edge> {
352 unsafe { Handle::new_edge(self, 0) }
354 }
355
356 pub(super) fn last_edge(self) -> Handle<Self, marker::Edge> {
357 let len = self.len();
358 unsafe { Handle::new_edge(self, len) }
360 }
361
362 pub(super) fn first_kv(self) -> Handle<Self, marker::KV> {
364 let len = self.len();
365 if !(len > 0) { ::core::panicking::panic("assertion failed: len > 0") };assert!(len > 0);
366 unsafe { Handle::new_kv(self, 0) }
368 }
369
370 pub(super) fn last_kv(self) -> Handle<Self, marker::KV> {
372 let len = self.len();
373 if !(len > 0) { ::core::panicking::panic("assertion failed: len > 0") };assert!(len > 0);
374 unsafe { Handle::new_kv(self, len - 1) }
376 }
377}
378
379impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
380 fn eq(&self, other: &Self) -> bool {
382 let Self { node, height, _marker } = self;
383 if node.eq(&other.node) {
384 if true {
{
match (&*height, &other.height) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(*height, other.height);
385 true
386 } else {
387 false
388 }
389 }
390}
391
392impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
393 fn into_leaf(self) -> &'a LeafNode<K, V> {
395 let ptr = Self::as_leaf_ptr(&self);
396 unsafe { &*ptr }
398 }
399
400 pub(super) fn keys(&self) -> &[K] {
402 let leaf = self.into_leaf();
403 unsafe { leaf.keys.get_unchecked(..usize::from(leaf.len)).assume_init_ref() }
405 }
406}
407
408impl<K, V> NodeRef<marker::Dying, K, V, marker::LeafOrInternal> {
409 pub(super) unsafe fn deallocate_and_ascend<A: AllocatorClone>(
413 self,
414 alloc: A,
415 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::Internal>, marker::Edge>> {
416 let height = self.height;
417 let node = self.node;
418 let ret = self.ascend().ok();
419 unsafe {
421 alloc.deallocate(
422 node.cast(),
423 if height > 0 {
424 Layout::new::<InternalNode<K, V>>()
425 } else {
426 Layout::new::<LeafNode<K, V>>()
427 },
428 );
429 }
430 ret
431 }
432 pub(super) unsafe fn drop_kvs(&mut self) {
439 struct DropGuard<'a, K, V> {
440 node: &'a NodeRef<marker::Dying, K, V, marker::LeafOrInternal>,
441 idx: usize,
442 }
443 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
444 fn drop(&mut self) {
445 let len = self.node.len();
446 for i in self.idx..len {
447 unsafe {
450 let kv = Handle::new_kv(ptr::read(self.node), i);
451 kv.drop_key_val();
452 }
453 }
454 }
455 }
456 let len = self.len();
457 for idx in 0..len {
458 let guard = DropGuard { node: self, idx: idx + 1 };
461 unsafe {
464 let kv = Handle::new_kv(ptr::read(self), idx);
465 kv.drop_key_val();
466 }
467
468 core::mem::forget(guard);
469 }
470 }
471}
472
473impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
474 unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
485 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
486 }
487
488 fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
490 let ptr = Self::as_leaf_ptr(self);
491 unsafe { &mut *ptr }
493 }
494
495 fn into_leaf_mut(mut self) -> &'a mut LeafNode<K, V> {
497 let ptr = Self::as_leaf_ptr(&mut self);
498 unsafe { &mut *ptr }
500 }
501
502 pub(super) fn dormant(&self) -> NodeRef<marker::DormantMut, K, V, Type> {
505 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
506 }
507}
508
509impl<K, V, Type> NodeRef<marker::DormantMut, K, V, Type> {
510 pub(super) unsafe fn awaken<'a>(self) -> NodeRef<marker::Mut<'a>, K, V, Type> {
517 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
518 }
519}
520
521impl<K, V, Type> NodeRef<marker::Dying, K, V, Type> {
522 fn as_leaf_dying(&mut self) -> &mut LeafNode<K, V> {
524 let ptr = Self::as_leaf_ptr(self);
525 unsafe { &mut *ptr }
527 }
528}
529
530impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
531 unsafe fn key_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
536 where
537 I: SliceIndex<[MaybeUninit<K>], Output = Output>,
538 {
539 unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) }
543 }
544
545 unsafe fn val_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
550 where
551 I: SliceIndex<[MaybeUninit<V>], Output = Output>,
552 {
553 unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) }
557 }
558}
559
560impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
561 unsafe fn edge_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
566 where
567 I: SliceIndex<[MaybeUninit<BoxedNode<K, V>>], Output = Output>,
568 {
569 unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) }
573 }
574}
575
576impl<'a, K, V, Type> NodeRef<marker::ValMut<'a>, K, V, Type> {
577 unsafe fn into_key_val_mut_at(mut self, idx: usize) -> (&'a K, &'a mut V) {
580 let leaf = Self::as_leaf_ptr(&mut self);
584 let keys = unsafe { &raw const (*leaf).keys };
586 let vals = unsafe { &raw mut (*leaf).vals };
588 let keys: *const [_] = keys;
590 let vals: *mut [_] = vals;
591 let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() };
593 let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() };
595 (key, val)
596 }
597}
598
599impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
600 pub(super) fn len_mut(&mut self) -> &mut u16 {
602 &mut self.as_leaf_mut().len
603 }
604}
605
606impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
607 unsafe fn correct_childrens_parent_links<R: Iterator<Item = usize>>(&mut self, range: R) {
610 for i in range {
611 if true {
if !(i <= self.len()) {
::core::panicking::panic("assertion failed: i <= self.len()")
};
};debug_assert!(i <= self.len());
612 unsafe { Handle::new_edge(self.reborrow_mut(), i) }.correct_parent_link();
614 }
615 }
616
617 fn correct_all_childrens_parent_links(&mut self) {
618 let len = self.len();
619 unsafe { self.correct_childrens_parent_links(0..=len) };
621 }
622}
623
624impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
625 fn set_parent_link(&mut self, parent: NonNull<InternalNode<K, V>>, parent_idx: usize) {
628 let leaf = Self::as_leaf_ptr(self);
629 unsafe { (*leaf).parent = Some(parent) };
631 unsafe { (*leaf).parent_idx.write(parent_idx as u16) };
633 }
634}
635
636impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
637 fn clear_parent_link(&mut self) {
639 let mut root_node = self.borrow_mut();
640 let leaf = root_node.as_leaf_mut();
641 leaf.parent = None;
642 }
643}
644
645impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
646 pub(super) fn new<A: AllocatorClone>(alloc: A) -> Self {
648 NodeRef::new_leaf(alloc).forget_type()
649 }
650
651 pub(super) fn push_internal_level<A: AllocatorClone>(
655 &mut self,
656 alloc: A,
657 ) -> NodeRef<marker::Mut<'_>, K, V, marker::Internal> {
658 super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root, alloc).forget_type());
659
660 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
662 }
663
664 pub(super) fn pop_internal_level<A: AllocatorClone>(&mut self, alloc: A) {
674 if !(self.height > 0) {
::core::panicking::panic("assertion failed: self.height > 0")
};assert!(self.height > 0);
675
676 let top = self.node;
677
678 let mut internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() };
680 let internal_node = internal_self.as_internal_mut();
681 self.node = unsafe { internal_node.edges[0].assume_init_read() };
683 self.height -= 1;
684 self.clear_parent_link();
685
686 unsafe {
688 alloc.deallocate(top.cast(), Layout::new::<InternalNode<K, V>>());
689 }
690 }
691}
692
693impl<K, V, Type> NodeRef<marker::Owned, K, V, Type> {
694 pub(super) fn borrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
698 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
699 }
700
701 pub(super) fn borrow_valmut(&mut self) -> NodeRef<marker::ValMut<'_>, K, V, Type> {
703 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
704 }
705
706 pub(super) fn into_dying(self) -> NodeRef<marker::Dying, K, V, Type> {
709 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
710 }
711}
712
713impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
714 pub(super) unsafe fn push_with_handle<'b>(
721 &mut self,
722 key: K,
723 val: V,
724 ) -> Handle<NodeRef<marker::Mut<'b>, K, V, marker::Leaf>, marker::KV> {
725 let len = self.len_mut();
726 let idx = usize::from(*len);
727 if !(idx < CAPACITY) {
::core::panicking::panic("assertion failed: idx < CAPACITY")
};assert!(idx < CAPACITY);
728 *len += 1;
729 unsafe {
731 self.key_area_mut(idx).write(key);
732 self.val_area_mut(idx).write(val);
733 Handle::new_kv(
734 NodeRef { height: self.height, node: self.node, _marker: PhantomData },
735 idx,
736 )
737 }
738 }
739
740 pub(super) fn push(&mut self, key: K, val: V) -> *mut V {
743 unsafe { self.push_with_handle(key, val).into_val_mut() }
745 }
746}
747
748impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
749 pub(super) fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
752 if !(edge.height == self.height - 1) {
::core::panicking::panic("assertion failed: edge.height == self.height - 1")
};assert!(edge.height == self.height - 1);
753
754 let len = self.len_mut();
755 let idx = usize::from(*len);
756 if !(idx < CAPACITY) {
::core::panicking::panic("assertion failed: idx < CAPACITY")
};assert!(idx < CAPACITY);
757 *len += 1;
758 unsafe {
760 self.key_area_mut(idx).write(key);
761 self.val_area_mut(idx).write(val);
762 self.edge_area_mut(idx + 1).write(edge.node);
763 Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
764 }
765 }
766}
767
768impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Leaf> {
769 pub(super) fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
771 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
772 }
773}
774
775impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
776 pub(super) fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
778 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
779 }
780}
781
782impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
783 pub(super) fn force(
785 self,
786 ) -> ForceResult<
787 NodeRef<BorrowType, K, V, marker::Leaf>,
788 NodeRef<BorrowType, K, V, marker::Internal>,
789 > {
790 if self.height == 0 {
791 ForceResult::Leaf(NodeRef {
792 height: self.height,
793 node: self.node,
794 _marker: PhantomData,
795 })
796 } else {
797 ForceResult::Internal(NodeRef {
798 height: self.height,
799 node: self.node,
800 _marker: PhantomData,
801 })
802 }
803 }
804}
805
806impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
807 pub(super) unsafe fn cast_to_leaf_unchecked(
809 self,
810 ) -> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
811 if true {
if !(self.height == 0) {
::core::panicking::panic("assertion failed: self.height == 0")
};
};debug_assert!(self.height == 0);
812 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
813 }
814
815 unsafe fn cast_to_internal_unchecked(self) -> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
817 if true {
if !(self.height > 0) {
::core::panicking::panic("assertion failed: self.height > 0")
};
};debug_assert!(self.height > 0);
818 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
819 }
820}
821
822pub(super) struct Handle<Node, Type> {
831 node: Node,
832 idx: usize,
833 _marker: PhantomData<Type>,
834}
835
836impl<Node: Copy, Type> Copy for Handle<Node, Type> {}
837impl<Node: Copy, Type> Clone for Handle<Node, Type> {
840 fn clone(&self) -> Self {
841 *self
842 }
843}
844
845impl<Node, Type> Handle<Node, Type> {
846 pub(super) fn into_node(self) -> Node {
848 self.node
849 }
850
851 pub(super) fn idx(&self) -> usize {
853 self.idx
854 }
855}
856
857impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
858 pub(super) unsafe fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
861 if true {
if !(idx < node.len()) {
::core::panicking::panic("assertion failed: idx < node.len()")
};
};debug_assert!(idx < node.len());
862
863 Handle { node, idx, _marker: PhantomData }
864 }
865
866 pub(super) fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
867 unsafe { Handle::new_edge(self.node, self.idx) }
869 }
870
871 pub(super) fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
872 unsafe { Handle::new_edge(self.node, self.idx + 1) }
874 }
875}
876
877impl<BorrowType, K, V, NodeType, HandleType> PartialEq
878 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
879{
880 fn eq(&self, other: &Self) -> bool {
881 let Self { node, idx, _marker } = self;
882 node.eq(&other.node) && *idx == other.idx
883 }
884}
885
886impl<BorrowType, K, V, NodeType, HandleType>
887 Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
888{
889 pub(super) fn reborrow(
891 &self,
892 ) -> Handle<NodeRef<marker::Immut<'_>, K, V, NodeType>, HandleType> {
893 Handle { node: self.node.reborrow(), idx: self.idx, _marker: PhantomData }
895 }
896}
897
898impl<'a, K, V, NodeType, HandleType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
899 pub(super) unsafe fn reborrow_mut(
905 &mut self,
906 ) -> Handle<NodeRef<marker::Mut<'_>, K, V, NodeType>, HandleType> {
907 Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData }
910 }
911
912 pub(super) fn dormant(
916 &self,
917 ) -> Handle<NodeRef<marker::DormantMut, K, V, NodeType>, HandleType> {
918 Handle { node: self.node.dormant(), idx: self.idx, _marker: PhantomData }
919 }
920}
921
922impl<K, V, NodeType, HandleType> Handle<NodeRef<marker::DormantMut, K, V, NodeType>, HandleType> {
923 pub(super) unsafe fn awaken<'a>(
930 self,
931 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
932 Handle { node: unsafe { self.node.awaken() }, idx: self.idx, _marker: PhantomData }
934 }
935}
936
937impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
938 pub(super) unsafe fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
941 if true {
if !(idx <= node.len()) {
::core::panicking::panic("assertion failed: idx <= node.len()")
};
};debug_assert!(idx <= node.len());
942
943 Handle { node, idx, _marker: PhantomData }
944 }
945
946 pub(super) fn left_kv(
947 self,
948 ) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
949 if self.idx > 0 {
950 Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) })
952 } else {
953 Err(self)
954 }
955 }
956
957 pub(super) fn right_kv(
958 self,
959 ) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
960 if self.idx < self.node.len() {
961 Ok(unsafe { Handle::new_kv(self.node, self.idx) })
963 } else {
964 Err(self)
965 }
966 }
967}
968
969pub(super) enum LeftOrRight<T> {
970 Left(T),
971 Right(T),
972}
973
974fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight<usize>) {
980 if true {
if !(edge_idx <= CAPACITY) {
::core::panicking::panic("assertion failed: edge_idx <= CAPACITY")
};
};debug_assert!(edge_idx <= CAPACITY);
981 match edge_idx {
983 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)),
984 EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)),
985 EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)),
986 _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))),
987 }
988}
989
990impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
991 unsafe fn insert_fit(
995 mut self,
996 key: K,
997 val: V,
998 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
999 if true {
if !(self.node.len() < CAPACITY) {
::core::panicking::panic("assertion failed: self.node.len() < CAPACITY")
};
};debug_assert!(self.node.len() < CAPACITY);
1000 let new_len = self.node.len() + 1;
1001
1002 unsafe {
1004 slice_insert(self.node.key_area_mut(..new_len), self.idx, key);
1005 slice_insert(self.node.val_area_mut(..new_len), self.idx, val);
1006 *self.node.len_mut() = new_len as u16;
1007
1008 Handle::new_kv(self.node, self.idx)
1009 }
1010 }
1011}
1012
1013impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
1014 fn insert<A: AllocatorClone>(
1020 self,
1021 key: K,
1022 val: V,
1023 alloc: A,
1024 ) -> (
1025 Option<SplitResult<'a, K, V, marker::Leaf>>,
1026 Handle<NodeRef<marker::DormantMut, K, V, marker::Leaf>, marker::KV>,
1027 ) {
1028 if self.node.len() < CAPACITY {
1029 let handle = unsafe { self.insert_fit(key, val) };
1031 (None, handle.dormant())
1032 } else {
1033 let (middle_kv_idx, insertion) = splitpoint(self.idx);
1034 let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
1036 let mut result = middle.split(alloc);
1037 let insertion_edge = match insertion {
1038 LeftOrRight::Left(insert_idx) => unsafe {
1040 Handle::new_edge(result.left.reborrow_mut(), insert_idx)
1041 },
1042 LeftOrRight::Right(insert_idx) => unsafe {
1044 Handle::new_edge(result.right.borrow_mut(), insert_idx)
1045 },
1046 };
1047 let handle = unsafe { insertion_edge.insert_fit(key, val).dormant() };
1050 (Some(result), handle)
1051 }
1052 }
1053}
1054
1055impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1056 fn correct_parent_link(self) {
1059 let ptr = unsafe { NonNull::new_unchecked(NodeRef::as_internal_ptr(&self.node)) };
1062 let idx = self.idx;
1063 let mut child = self.descend();
1064 child.set_parent_link(ptr, idx);
1065 }
1066}
1067
1068impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1069 fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
1073 if true {
if !(self.node.len() < CAPACITY) {
::core::panicking::panic("assertion failed: self.node.len() < CAPACITY")
};
};debug_assert!(self.node.len() < CAPACITY);
1074 if true {
if !(edge.height == self.node.height - 1) {
::core::panicking::panic("assertion failed: edge.height == self.node.height - 1")
};
};debug_assert!(edge.height == self.node.height - 1);
1075 let new_len = self.node.len() + 1;
1076
1077 unsafe {
1079 slice_insert(self.node.key_area_mut(..new_len), self.idx, key);
1080 slice_insert(self.node.val_area_mut(..new_len), self.idx, val);
1081 slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node);
1082 *self.node.len_mut() = new_len as u16;
1083
1084 self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1);
1085 }
1086 }
1087
1088 fn insert<A: AllocatorClone>(
1092 mut self,
1093 key: K,
1094 val: V,
1095 edge: Root<K, V>,
1096 alloc: A,
1097 ) -> Option<SplitResult<'a, K, V, marker::Internal>> {
1098 if !(edge.height == self.node.height - 1) {
::core::panicking::panic("assertion failed: edge.height == self.node.height - 1")
};assert!(edge.height == self.node.height - 1);
1099
1100 if self.node.len() < CAPACITY {
1101 self.insert_fit(key, val, edge);
1102 None
1103 } else {
1104 let (middle_kv_idx, insertion) = splitpoint(self.idx);
1105 let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
1107 let mut result = middle.split(alloc);
1108 let mut insertion_edge = match insertion {
1109 LeftOrRight::Left(insert_idx) => unsafe {
1111 Handle::new_edge(result.left.reborrow_mut(), insert_idx)
1112 },
1113 LeftOrRight::Right(insert_idx) => unsafe {
1115 Handle::new_edge(result.right.borrow_mut(), insert_idx)
1116 },
1117 };
1118 insertion_edge.insert_fit(key, val, edge);
1119 Some(result)
1120 }
1121 }
1122}
1123
1124impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
1125 pub(super) fn insert_recursing<A: AllocatorClone>(
1133 self,
1134 key: K,
1135 value: V,
1136 alloc: A,
1137 split_root: impl FnOnce(SplitResult<'a, K, V, marker::LeafOrInternal>),
1138 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1139 let (mut split, handle) = match self.insert(key, value, alloc.clone()) {
1140 (None, handle) => return unsafe { handle.awaken() },
1143 (Some(split), handle) => (split.forget_node_type(), handle),
1144 };
1145
1146 loop {
1147 split = match split.left.ascend() {
1148 Ok(parent) => {
1149 match parent.insert(split.kv.0, split.kv.1, split.right, alloc.clone()) {
1150 None => return unsafe { handle.awaken() },
1153 Some(split) => split.forget_node_type(),
1154 }
1155 }
1156 Err(root) => {
1157 split_root(SplitResult { left: root, ..split });
1158 return unsafe { handle.awaken() };
1161 }
1162 };
1163 }
1164 }
1165}
1166
1167impl<BorrowType: marker::BorrowType, K, V>
1168 Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>
1169{
1170 pub(super) fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1177 const {
1178 if !BorrowType::TRAVERSAL_PERMIT {
::core::panicking::panic("assertion failed: BorrowType::TRAVERSAL_PERMIT")
};assert!(BorrowType::TRAVERSAL_PERMIT);
1179 }
1180
1181 let parent_ptr = NodeRef::as_internal_ptr(&self.node);
1189 let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() };
1191 NodeRef { node, height: self.node.height - 1, _marker: PhantomData }
1192 }
1193}
1194
1195impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
1196 pub(super) fn into_kv(self) -> (&'a K, &'a V) {
1197 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1198 let leaf = self.node.into_leaf();
1199 let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() };
1201 let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() };
1203 (k, v)
1204 }
1205}
1206
1207impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1208 pub(super) fn key_mut(&mut self) -> &mut K {
1209 unsafe { self.node.key_area_mut(self.idx).assume_init_mut() }
1211 }
1212
1213 pub(super) fn into_val_mut(self) -> &'a mut V {
1214 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1215 let leaf = self.node.into_leaf_mut();
1216 unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() }
1218 }
1219
1220 pub(super) fn into_kv_mut(self) -> (&'a mut K, &'a mut V) {
1221 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1222 let leaf = self.node.into_leaf_mut();
1223 let k = unsafe { leaf.keys.get_unchecked_mut(self.idx).assume_init_mut() };
1225 let v = unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() };
1227 (k, v)
1228 }
1229}
1230
1231impl<'a, K, V, NodeType> Handle<NodeRef<marker::ValMut<'a>, K, V, NodeType>, marker::KV> {
1232 pub(super) fn into_kv_valmut(self) -> (&'a K, &'a mut V) {
1233 unsafe { self.node.into_key_val_mut_at(self.idx) }
1235 }
1236}
1237
1238impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1239 pub(super) fn kv_mut(&mut self) -> (&mut K, &mut V) {
1240 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1241 unsafe {
1245 let leaf = self.node.as_leaf_mut();
1246 let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut();
1247 let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut();
1248 (key, val)
1249 }
1250 }
1251
1252 pub(super) fn replace_kv(&mut self, k: K, v: V) -> (K, V) {
1254 let (key, val) = self.kv_mut();
1255 (mem::replace(key, k), mem::replace(val, v))
1256 }
1257}
1258
1259impl<K, V, NodeType> Handle<NodeRef<marker::Dying, K, V, NodeType>, marker::KV> {
1260 pub(super) unsafe fn into_key_val(mut self) -> (K, V) {
1264 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1265 let leaf = self.node.as_leaf_dying();
1266 unsafe {
1268 let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_read();
1269 let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_read();
1270 (key, val)
1271 }
1272 }
1273
1274 #[inline]
1278 pub(super) unsafe fn drop_key_val(mut self) {
1279 struct Dropper<'a, T>(&'a mut MaybeUninit<T>);
1281 impl<T> Drop for Dropper<'_, T> {
1282 #[inline]
1283 fn drop(&mut self) {
1284 unsafe {
1286 self.0.assume_init_drop();
1287 }
1288 }
1289 }
1290
1291 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1292 let leaf = self.node.as_leaf_dying();
1293 unsafe {
1295 let key = leaf.keys.get_unchecked_mut(self.idx);
1296 let val = leaf.vals.get_unchecked_mut(self.idx);
1297 let _guard = Dropper(val);
1298 key.assume_init_drop();
1299 }
1301 }
1302}
1303
1304impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1305 fn split_leaf_data(&mut self, new_node: &mut LeafNode<K, V>) -> (K, V) {
1308 if true {
if !(self.idx < self.node.len()) {
::core::panicking::panic("assertion failed: self.idx < self.node.len()")
};
};debug_assert!(self.idx < self.node.len());
1309 let old_len = self.node.len();
1310 let new_len = old_len - self.idx - 1;
1311 new_node.len = new_len as u16;
1312 unsafe {
1314 let k = self.node.key_area_mut(self.idx).assume_init_read();
1315 let v = self.node.val_area_mut(self.idx).assume_init_read();
1316
1317 move_to_slice(
1318 self.node.key_area_mut(self.idx + 1..old_len),
1319 &mut new_node.keys[..new_len],
1320 );
1321 move_to_slice(
1322 self.node.val_area_mut(self.idx + 1..old_len),
1323 &mut new_node.vals[..new_len],
1324 );
1325
1326 *self.node.len_mut() = self.idx as u16;
1327 (k, v)
1328 }
1329 }
1330}
1331
1332impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1333 pub(super) fn split<A: AllocatorClone>(
1341 mut self,
1342 alloc: A,
1343 ) -> SplitResult<'a, K, V, marker::Leaf> {
1344 let mut new_node = LeafNode::new(alloc);
1345
1346 let kv = self.split_leaf_data(&mut new_node);
1347
1348 let right = NodeRef::from_new_leaf(new_node);
1349 SplitResult { left: self.node, kv, right }
1350 }
1351
1352 pub(super) fn remove(
1355 mut self,
1356 ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
1357 let old_len = self.node.len();
1358 unsafe {
1360 let k = slice_remove(self.node.key_area_mut(..old_len), self.idx);
1361 let v = slice_remove(self.node.val_area_mut(..old_len), self.idx);
1362 *self.node.len_mut() = (old_len - 1) as u16;
1363 ((k, v), self.left_edge())
1364 }
1365 }
1366}
1367
1368impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1369 pub(super) fn split<A: AllocatorClone>(
1377 mut self,
1378 alloc: A,
1379 ) -> SplitResult<'a, K, V, marker::Internal> {
1380 let old_len = self.node.len();
1381 unsafe {
1383 let mut new_node = InternalNode::new(alloc);
1384 let kv = self.split_leaf_data(&mut new_node.data);
1385 let new_len = usize::from(new_node.data.len);
1386 move_to_slice(
1387 self.node.edge_area_mut(self.idx + 1..old_len + 1),
1388 &mut new_node.edges[..new_len + 1],
1389 );
1390
1391 let height = NonZero::new_unchecked(self.node.height);
1393 let right = NodeRef::from_new_internal(new_node, height);
1394
1395 SplitResult { left: self.node, kv, right }
1396 }
1397 }
1398}
1399
1400pub(super) struct BalancingContext<'a, K, V> {
1403 parent: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV>,
1404 left_child: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1405 right_child: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1406}
1407
1408impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1409 pub(super) fn consider_for_balancing(self) -> BalancingContext<'a, K, V> {
1410 let self1 = unsafe { ptr::read(&self) };
1412 let self2 = unsafe { ptr::read(&self) };
1414 BalancingContext {
1415 parent: self,
1416 left_child: self1.left_edge().descend(),
1417 right_child: self2.right_edge().descend(),
1418 }
1419 }
1420}
1421
1422impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1423 pub(super) fn choose_parent_kv(self) -> Result<LeftOrRight<BalancingContext<'a, K, V>>, Self> {
1438 match unsafe { ptr::read(&self) }.ascend() {
1440 Ok(parent_edge) => match parent_edge.left_kv() {
1441 Ok(left_parent_kv) => Ok(LeftOrRight::Left(BalancingContext {
1442 parent: unsafe { ptr::read(&left_parent_kv) },
1444 left_child: left_parent_kv.left_edge().descend(),
1445 right_child: self,
1446 })),
1447 Err(parent_edge) => match parent_edge.right_kv() {
1448 Ok(right_parent_kv) => Ok(LeftOrRight::Right(BalancingContext {
1449 parent: unsafe { ptr::read(&right_parent_kv) },
1451 left_child: self,
1452 right_child: right_parent_kv.right_edge().descend(),
1453 })),
1454 Err(_) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("empty internal node")));
}unreachable!("empty internal node"),
1455 },
1456 },
1457 Err(root) => Err(root),
1458 }
1459 }
1460}
1461
1462impl<'a, K, V> BalancingContext<'a, K, V> {
1463 pub(super) fn left_child_len(&self) -> usize {
1464 self.left_child.len()
1465 }
1466
1467 pub(super) fn right_child_len(&self) -> usize {
1468 self.right_child.len()
1469 }
1470
1471 pub(super) fn into_left_child(self) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1472 self.left_child
1473 }
1474
1475 pub(super) fn into_right_child(self) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1476 self.right_child
1477 }
1478
1479 pub(super) fn can_merge(&self) -> bool {
1482 self.left_child.len() + 1 + self.right_child.len() <= CAPACITY
1483 }
1484}
1485
1486impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> {
1487 fn do_merge<
1489 F: FnOnce(
1490 NodeRef<marker::Mut<'a>, K, V, marker::Internal>,
1491 NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1492 ) -> R,
1493 R,
1494 A: Allocator,
1495 >(
1496 self,
1497 result: F,
1498 alloc: A,
1499 ) -> R {
1500 let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent;
1501 let old_parent_len = parent_node.len();
1502 let mut left_node = self.left_child;
1503 let old_left_len = left_node.len();
1504 let mut right_node = self.right_child;
1505 let right_len = right_node.len();
1506 let new_left_len = old_left_len + 1 + right_len;
1507
1508 if !(new_left_len <= CAPACITY) {
::core::panicking::panic("assertion failed: new_left_len <= CAPACITY")
};assert!(new_left_len <= CAPACITY);
1509
1510 unsafe {
1512 *left_node.len_mut() = new_left_len as u16;
1513
1514 let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx);
1515 left_node.key_area_mut(old_left_len).write(parent_key);
1516 move_to_slice(
1517 right_node.key_area_mut(..right_len),
1518 left_node.key_area_mut(old_left_len + 1..new_left_len),
1519 );
1520
1521 let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx);
1522 left_node.val_area_mut(old_left_len).write(parent_val);
1523 move_to_slice(
1524 right_node.val_area_mut(..right_len),
1525 left_node.val_area_mut(old_left_len + 1..new_left_len),
1526 );
1527
1528 slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1);
1529 parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len);
1530 *parent_node.len_mut() -= 1;
1531
1532 if parent_node.height > 1 {
1533 let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked();
1536 let mut right_node = right_node.cast_to_internal_unchecked();
1537 move_to_slice(
1538 right_node.edge_area_mut(..right_len + 1),
1539 left_node.edge_area_mut(old_left_len + 1..new_left_len + 1),
1540 );
1541
1542 left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1);
1543
1544 alloc.deallocate(right_node.node.cast(), Layout::new::<InternalNode<K, V>>());
1545 } else {
1546 alloc.deallocate(right_node.node.cast(), Layout::new::<LeafNode<K, V>>());
1547 }
1548 }
1549 result(parent_node, left_node)
1550 }
1551
1552 pub(super) fn merge_tracking_parent<A: AllocatorClone>(
1557 self,
1558 alloc: A,
1559 ) -> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
1560 self.do_merge(|parent, _child| parent, alloc)
1561 }
1562
1563 pub(super) fn merge_tracking_child<A: AllocatorClone>(
1568 self,
1569 alloc: A,
1570 ) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1571 self.do_merge(|_parent, child| child, alloc)
1572 }
1573
1574 pub(super) fn merge_tracking_child_edge<A: AllocatorClone>(
1580 self,
1581 track_edge_idx: LeftOrRight<usize>,
1582 alloc: A,
1583 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1584 let old_left_len = self.left_child.len();
1585 let right_len = self.right_child.len();
1586 if !match track_edge_idx {
LeftOrRight::Left(idx) => idx <= old_left_len,
LeftOrRight::Right(idx) => idx <= right_len,
} {
::core::panicking::panic("assertion failed: match track_edge_idx {\n LeftOrRight::Left(idx) => idx <= old_left_len,\n LeftOrRight::Right(idx) => idx <= right_len,\n}")
};assert!(match track_edge_idx {
1587 LeftOrRight::Left(idx) => idx <= old_left_len,
1588 LeftOrRight::Right(idx) => idx <= right_len,
1589 });
1590 let child = self.merge_tracking_child(alloc);
1591 let new_idx = match track_edge_idx {
1592 LeftOrRight::Left(idx) => idx,
1593 LeftOrRight::Right(idx) => old_left_len + 1 + idx,
1594 };
1595 unsafe { Handle::new_edge(child, new_idx) }
1597 }
1598
1599 pub(super) fn steal_left(
1604 mut self,
1605 track_right_edge_idx: usize,
1606 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1607 self.bulk_steal_left(1);
1608 unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) }
1610 }
1611
1612 pub(super) fn steal_right(
1617 mut self,
1618 track_left_edge_idx: usize,
1619 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1620 self.bulk_steal_right(1);
1621 unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) }
1623 }
1624
1625 pub(super) fn bulk_steal_left(&mut self, count: usize) {
1627 if !(count > 0) { ::core::panicking::panic("assertion failed: count > 0") };assert!(count > 0);
1628 unsafe {
1630 let left_node = &mut self.left_child;
1631 let old_left_len = left_node.len();
1632 let right_node = &mut self.right_child;
1633 let old_right_len = right_node.len();
1634
1635 if !(old_right_len + count <= CAPACITY) {
::core::panicking::panic("assertion failed: old_right_len + count <= CAPACITY")
};assert!(old_right_len + count <= CAPACITY);
1637 if !(old_left_len >= count) {
::core::panicking::panic("assertion failed: old_left_len >= count")
};assert!(old_left_len >= count);
1638
1639 let new_left_len = old_left_len - count;
1640 let new_right_len = old_right_len + count;
1641 *left_node.len_mut() = new_left_len as u16;
1642 *right_node.len_mut() = new_right_len as u16;
1643
1644 {
1646 slice_shr(right_node.key_area_mut(..new_right_len), count);
1648 slice_shr(right_node.val_area_mut(..new_right_len), count);
1649
1650 move_to_slice(
1652 left_node.key_area_mut(new_left_len + 1..old_left_len),
1653 right_node.key_area_mut(..count - 1),
1654 );
1655 move_to_slice(
1656 left_node.val_area_mut(new_left_len + 1..old_left_len),
1657 right_node.val_area_mut(..count - 1),
1658 );
1659
1660 let k = left_node.key_area_mut(new_left_len).assume_init_read();
1662 let v = left_node.val_area_mut(new_left_len).assume_init_read();
1663 let (k, v) = self.parent.replace_kv(k, v);
1664
1665 right_node.key_area_mut(count - 1).write(k);
1667 right_node.val_area_mut(count - 1).write(v);
1668 }
1669
1670 match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) {
1671 (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1672 slice_shr(right.edge_area_mut(..new_right_len + 1), count);
1674
1675 move_to_slice(
1677 left.edge_area_mut(new_left_len + 1..old_left_len + 1),
1678 right.edge_area_mut(..count),
1679 );
1680
1681 right.correct_childrens_parent_links(0..new_right_len + 1);
1682 }
1683 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1684 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1685 }
1686 }
1687 }
1688
1689 pub(super) fn bulk_steal_right(&mut self, count: usize) {
1691 if !(count > 0) { ::core::panicking::panic("assertion failed: count > 0") };assert!(count > 0);
1692 unsafe {
1694 let left_node = &mut self.left_child;
1695 let old_left_len = left_node.len();
1696 let right_node = &mut self.right_child;
1697 let old_right_len = right_node.len();
1698
1699 if !(old_left_len + count <= CAPACITY) {
::core::panicking::panic("assertion failed: old_left_len + count <= CAPACITY")
};assert!(old_left_len + count <= CAPACITY);
1701 if !(old_right_len >= count) {
::core::panicking::panic("assertion failed: old_right_len >= count")
};assert!(old_right_len >= count);
1702
1703 let new_left_len = old_left_len + count;
1704 let new_right_len = old_right_len - count;
1705 *left_node.len_mut() = new_left_len as u16;
1706 *right_node.len_mut() = new_right_len as u16;
1707
1708 {
1710 let k = right_node.key_area_mut(count - 1).assume_init_read();
1712 let v = right_node.val_area_mut(count - 1).assume_init_read();
1713 let (k, v) = self.parent.replace_kv(k, v);
1714
1715 left_node.key_area_mut(old_left_len).write(k);
1717 left_node.val_area_mut(old_left_len).write(v);
1718
1719 move_to_slice(
1721 right_node.key_area_mut(..count - 1),
1722 left_node.key_area_mut(old_left_len + 1..new_left_len),
1723 );
1724 move_to_slice(
1725 right_node.val_area_mut(..count - 1),
1726 left_node.val_area_mut(old_left_len + 1..new_left_len),
1727 );
1728
1729 slice_shl(right_node.key_area_mut(..old_right_len), count);
1731 slice_shl(right_node.val_area_mut(..old_right_len), count);
1732 }
1733
1734 match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) {
1735 (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1736 move_to_slice(
1738 right.edge_area_mut(..count),
1739 left.edge_area_mut(old_left_len + 1..new_left_len + 1),
1740 );
1741
1742 slice_shl(right.edge_area_mut(..old_right_len + 1), count);
1744
1745 left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1);
1746 right.correct_childrens_parent_links(0..new_right_len + 1);
1747 }
1748 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1749 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1750 }
1751 }
1752 }
1753}
1754
1755impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1756 pub(super) fn forget_node_type(
1757 self,
1758 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1759 unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1761 }
1762}
1763
1764impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1765 pub(super) fn forget_node_type(
1766 self,
1767 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1768 unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1770 }
1771}
1772
1773impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::KV> {
1774 pub(super) fn forget_node_type(
1775 self,
1776 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1777 unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1779 }
1780}
1781
1782impl<BorrowType, K, V, Type> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, Type> {
1783 pub(super) fn force(
1785 self,
1786 ) -> ForceResult<
1787 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, Type>,
1788 Handle<NodeRef<BorrowType, K, V, marker::Internal>, Type>,
1789 > {
1790 match self.node.force() {
1791 ForceResult::Leaf(node) => {
1792 ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData })
1793 }
1794 ForceResult::Internal(node) => {
1795 ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData })
1796 }
1797 }
1798 }
1799}
1800
1801impl<'a, K, V, Type> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, Type> {
1802 pub(super) unsafe fn cast_to_leaf_unchecked(
1804 self,
1805 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, Type> {
1806 let node = unsafe { self.node.cast_to_leaf_unchecked() };
1808 Handle { node, idx: self.idx, _marker: PhantomData }
1809 }
1810}
1811
1812impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1813 pub(super) fn move_suffix(
1816 &mut self,
1817 right: &mut NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1818 ) {
1819 unsafe {
1821 let new_left_len = self.idx;
1822 let mut left_node = self.reborrow_mut().into_node();
1823 let old_left_len = left_node.len();
1824
1825 let new_right_len = old_left_len - new_left_len;
1826 let mut right_node = right.reborrow_mut();
1827
1828 if !(right_node.len() == 0) {
::core::panicking::panic("assertion failed: right_node.len() == 0")
};assert!(right_node.len() == 0);
1829 if !(left_node.height == right_node.height) {
::core::panicking::panic("assertion failed: left_node.height == right_node.height")
};assert!(left_node.height == right_node.height);
1830
1831 if new_right_len > 0 {
1832 *left_node.len_mut() = new_left_len as u16;
1833 *right_node.len_mut() = new_right_len as u16;
1834
1835 move_to_slice(
1836 left_node.key_area_mut(new_left_len..old_left_len),
1837 right_node.key_area_mut(..new_right_len),
1838 );
1839 move_to_slice(
1840 left_node.val_area_mut(new_left_len..old_left_len),
1841 right_node.val_area_mut(..new_right_len),
1842 );
1843 match (left_node.force(), right_node.force()) {
1844 (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1845 move_to_slice(
1846 left.edge_area_mut(new_left_len + 1..old_left_len + 1),
1847 right.edge_area_mut(1..new_right_len + 1),
1848 );
1849 right.correct_childrens_parent_links(1..new_right_len + 1);
1850 }
1851 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1852 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1853 }
1854 }
1855 }
1856 }
1857}
1858
1859pub(super) enum ForceResult<Leaf, Internal> {
1860 Leaf(Leaf),
1861 Internal(Internal),
1862}
1863
1864pub(super) struct SplitResult<'a, K, V, NodeType> {
1866 pub left: NodeRef<marker::Mut<'a>, K, V, NodeType>,
1868 pub kv: (K, V),
1870 pub right: NodeRef<marker::Owned, K, V, NodeType>,
1872}
1873
1874impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> {
1875 pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> {
1876 SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() }
1877 }
1878}
1879
1880impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> {
1881 pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> {
1882 SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() }
1883 }
1884}
1885
1886pub(super) mod marker {
1887 use core::marker::PhantomData;
1888
1889 pub(crate) enum Leaf {}
1890 pub(crate) enum Internal {}
1891 pub(crate) enum LeafOrInternal {}
1892
1893 pub(crate) enum Owned {}
1894 pub(crate) enum Dying {}
1895 pub(crate) enum DormantMut {}
1896 pub(crate) struct Immut<'a>(PhantomData<&'a ()>);
1897 pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>);
1898 pub(crate) struct ValMut<'a>(PhantomData<&'a mut ()>);
1899
1900 pub(crate) trait BorrowType {
1901 const TRAVERSAL_PERMIT: bool = true;
1905 }
1906 impl BorrowType for Owned {
1907 const TRAVERSAL_PERMIT: bool = false;
1912 }
1913 impl BorrowType for Dying {}
1914 impl<'a> BorrowType for Immut<'a> {}
1915 impl<'a> BorrowType for Mut<'a> {}
1916 impl<'a> BorrowType for ValMut<'a> {}
1917 impl BorrowType for DormantMut {}
1918
1919 pub(crate) enum KV {}
1920 pub(crate) enum Edge {}
1921}
1922
1923unsafe fn slice_insert<T>(slice: &mut [MaybeUninit<T>], idx: usize, val: T) {
1928 let len = slice.len();
1929 if true {
if !(len > idx) {
::core::panicking::panic("assertion failed: len > idx")
};
};debug_assert!(len > idx);
1930 let slice_ptr = slice.as_mut_ptr();
1931 unsafe {
1933 if len > idx + 1 {
1934 ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1);
1935 }
1936 (*slice_ptr.add(idx)).write(val);
1937 }
1938}
1939
1940unsafe fn slice_remove<T>(slice: &mut [MaybeUninit<T>], idx: usize) -> T {
1946 let len = slice.len();
1947 if true {
if !(idx < len) {
::core::panicking::panic("assertion failed: idx < len")
};
};debug_assert!(idx < len);
1948 let slice_ptr = slice.as_mut_ptr();
1949 unsafe {
1951 let ret = (*slice_ptr.add(idx)).assume_init_read();
1952 ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1);
1953 ret
1954 }
1955}
1956
1957unsafe fn slice_shl<T>(slice: &mut [MaybeUninit<T>], distance: usize) {
1962 let slice_ptr = slice.as_mut_ptr();
1963 unsafe {
1965 ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance);
1966 }
1967}
1968
1969unsafe fn slice_shr<T>(slice: &mut [MaybeUninit<T>], distance: usize) {
1974 let slice_ptr = slice.as_mut_ptr();
1975 unsafe {
1977 ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance);
1978 }
1979}
1980
1981fn move_to_slice<T>(src: &mut [MaybeUninit<T>], dst: &mut [MaybeUninit<T>]) {
1985 if !(src.len() == dst.len()) {
::core::panicking::panic("assertion failed: src.len() == dst.len()")
};assert!(src.len() == dst.len());
1986 unsafe {
1988 ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());
1989 }
1990}
1991
1992#[cfg(test)]
1993mod tests;