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 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 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 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 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 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}
433
434impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
435 unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
446 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
447 }
448
449 fn as_leaf_mut(&mut self) -> &mut LeafNode<K, V> {
451 let ptr = Self::as_leaf_ptr(self);
452 unsafe { &mut *ptr }
454 }
455
456 fn into_leaf_mut(mut self) -> &'a mut LeafNode<K, V> {
458 let ptr = Self::as_leaf_ptr(&mut self);
459 unsafe { &mut *ptr }
461 }
462
463 pub(super) fn dormant(&self) -> NodeRef<marker::DormantMut, K, V, Type> {
466 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
467 }
468}
469
470impl<K, V, Type> NodeRef<marker::DormantMut, K, V, Type> {
471 pub(super) unsafe fn awaken<'a>(self) -> NodeRef<marker::Mut<'a>, K, V, Type> {
478 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
479 }
480}
481
482impl<K, V, Type> NodeRef<marker::Dying, K, V, Type> {
483 fn as_leaf_dying(&mut self) -> &mut LeafNode<K, V> {
485 let ptr = Self::as_leaf_ptr(self);
486 unsafe { &mut *ptr }
488 }
489}
490
491impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
492 unsafe fn key_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
497 where
498 I: SliceIndex<[MaybeUninit<K>], Output = Output>,
499 {
500 unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) }
504 }
505
506 unsafe fn val_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
511 where
512 I: SliceIndex<[MaybeUninit<V>], Output = Output>,
513 {
514 unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) }
518 }
519}
520
521impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
522 unsafe fn edge_area_mut<I, Output: ?Sized>(&mut self, index: I) -> &mut Output
527 where
528 I: SliceIndex<[MaybeUninit<BoxedNode<K, V>>], Output = Output>,
529 {
530 unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) }
534 }
535}
536
537impl<'a, K, V, Type> NodeRef<marker::ValMut<'a>, K, V, Type> {
538 unsafe fn into_key_val_mut_at(mut self, idx: usize) -> (&'a K, &'a mut V) {
541 let leaf = Self::as_leaf_ptr(&mut self);
545 let keys = unsafe { &raw const (*leaf).keys };
547 let vals = unsafe { &raw mut (*leaf).vals };
549 let keys: *const [_] = keys;
551 let vals: *mut [_] = vals;
552 let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() };
554 let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() };
556 (key, val)
557 }
558}
559
560impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
561 pub(super) fn len_mut(&mut self) -> &mut u16 {
563 &mut self.as_leaf_mut().len
564 }
565}
566
567impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
568 unsafe fn correct_childrens_parent_links<R: Iterator<Item = usize>>(&mut self, range: R) {
571 for i in range {
572 debug_assert!(i <= self.len());
573 unsafe { Handle::new_edge(self.reborrow_mut(), i) }.correct_parent_link();
575 }
576 }
577
578 fn correct_all_childrens_parent_links(&mut self) {
579 let len = self.len();
580 unsafe { self.correct_childrens_parent_links(0..=len) };
582 }
583}
584
585impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
586 fn set_parent_link(&mut self, parent: NonNull<InternalNode<K, V>>, parent_idx: usize) {
589 let leaf = Self::as_leaf_ptr(self);
590 unsafe { (*leaf).parent = Some(parent) };
592 unsafe { (*leaf).parent_idx.write(parent_idx as u16) };
594 }
595}
596
597impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
598 fn clear_parent_link(&mut self) {
600 let mut root_node = self.borrow_mut();
601 let leaf = root_node.as_leaf_mut();
602 leaf.parent = None;
603 }
604}
605
606impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
607 pub(super) fn new<A: AllocatorClone>(alloc: A) -> Self {
609 NodeRef::new_leaf(alloc).forget_type()
610 }
611
612 pub(super) fn push_internal_level<A: AllocatorClone>(
616 &mut self,
617 alloc: A,
618 ) -> NodeRef<marker::Mut<'_>, K, V, marker::Internal> {
619 super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root, alloc).forget_type());
620
621 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
623 }
624
625 pub(super) fn pop_internal_level<A: AllocatorClone>(&mut self, alloc: A) {
635 assert!(self.height > 0);
636
637 let top = self.node;
638
639 let mut internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() };
641 let internal_node = internal_self.as_internal_mut();
642 self.node = unsafe { internal_node.edges[0].assume_init_read() };
644 self.height -= 1;
645 self.clear_parent_link();
646
647 unsafe {
649 alloc.deallocate(top.cast(), Layout::new::<InternalNode<K, V>>());
650 }
651 }
652}
653
654impl<K, V, Type> NodeRef<marker::Owned, K, V, Type> {
655 pub(super) fn borrow_mut(&mut self) -> NodeRef<marker::Mut<'_>, K, V, Type> {
659 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
660 }
661
662 pub(super) fn borrow_valmut(&mut self) -> NodeRef<marker::ValMut<'_>, K, V, Type> {
664 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
665 }
666
667 pub(super) fn into_dying(self) -> NodeRef<marker::Dying, K, V, Type> {
670 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
671 }
672}
673
674impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
675 pub(super) unsafe fn push_with_handle<'b>(
682 &mut self,
683 key: K,
684 val: V,
685 ) -> Handle<NodeRef<marker::Mut<'b>, K, V, marker::Leaf>, marker::KV> {
686 let len = self.len_mut();
687 let idx = usize::from(*len);
688 assert!(idx < CAPACITY);
689 *len += 1;
690 unsafe {
692 self.key_area_mut(idx).write(key);
693 self.val_area_mut(idx).write(val);
694 Handle::new_kv(
695 NodeRef { height: self.height, node: self.node, _marker: PhantomData },
696 idx,
697 )
698 }
699 }
700
701 pub(super) fn push(&mut self, key: K, val: V) -> *mut V {
704 unsafe { self.push_with_handle(key, val).into_val_mut() }
706 }
707}
708
709impl<'a, K: 'a, V: 'a> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
710 pub(super) fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
713 assert!(edge.height == self.height - 1);
714
715 let len = self.len_mut();
716 let idx = usize::from(*len);
717 assert!(idx < CAPACITY);
718 *len += 1;
719 unsafe {
721 self.key_area_mut(idx).write(key);
722 self.val_area_mut(idx).write(val);
723 self.edge_area_mut(idx + 1).write(edge.node);
724 Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link();
725 }
726 }
727}
728
729impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Leaf> {
730 pub(super) fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
732 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
733 }
734}
735
736impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Internal> {
737 pub(super) fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
739 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
740 }
741}
742
743impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
744 pub(super) fn force(
746 self,
747 ) -> ForceResult<
748 NodeRef<BorrowType, K, V, marker::Leaf>,
749 NodeRef<BorrowType, K, V, marker::Internal>,
750 > {
751 if self.height == 0 {
752 ForceResult::Leaf(NodeRef {
753 height: self.height,
754 node: self.node,
755 _marker: PhantomData,
756 })
757 } else {
758 ForceResult::Internal(NodeRef {
759 height: self.height,
760 node: self.node,
761 _marker: PhantomData,
762 })
763 }
764 }
765}
766
767impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
768 pub(super) unsafe fn cast_to_leaf_unchecked(
770 self,
771 ) -> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
772 debug_assert!(self.height == 0);
773 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
774 }
775
776 unsafe fn cast_to_internal_unchecked(self) -> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
778 debug_assert!(self.height > 0);
779 NodeRef { height: self.height, node: self.node, _marker: PhantomData }
780 }
781}
782
783pub(super) struct Handle<Node, Type> {
792 node: Node,
793 idx: usize,
794 _marker: PhantomData<Type>,
795}
796
797impl<Node: Copy, Type> Copy for Handle<Node, Type> {}
798impl<Node: Copy, Type> Clone for Handle<Node, Type> {
801 fn clone(&self) -> Self {
802 *self
803 }
804}
805
806impl<Node, Type> Handle<Node, Type> {
807 pub(super) fn into_node(self) -> Node {
809 self.node
810 }
811
812 pub(super) fn idx(&self) -> usize {
814 self.idx
815 }
816}
817
818impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
819 pub(super) unsafe fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
822 debug_assert!(idx < node.len());
823
824 Handle { node, idx, _marker: PhantomData }
825 }
826
827 pub(super) fn left_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
828 unsafe { Handle::new_edge(self.node, self.idx) }
830 }
831
832 pub(super) fn right_edge(self) -> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
833 unsafe { Handle::new_edge(self.node, self.idx + 1) }
835 }
836}
837
838impl<BorrowType, K, V, NodeType, HandleType> PartialEq
839 for Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
840{
841 fn eq(&self, other: &Self) -> bool {
842 let Self { node, idx, _marker } = self;
843 node.eq(&other.node) && *idx == other.idx
844 }
845}
846
847impl<BorrowType, K, V, NodeType, HandleType>
848 Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType>
849{
850 pub(super) fn reborrow(
852 &self,
853 ) -> Handle<NodeRef<marker::Immut<'_>, K, V, NodeType>, HandleType> {
854 Handle { node: self.node.reborrow(), idx: self.idx, _marker: PhantomData }
856 }
857}
858
859impl<'a, K, V, NodeType, HandleType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
860 pub(super) unsafe fn reborrow_mut(
866 &mut self,
867 ) -> Handle<NodeRef<marker::Mut<'_>, K, V, NodeType>, HandleType> {
868 Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData }
871 }
872
873 pub(super) fn dormant(
877 &self,
878 ) -> Handle<NodeRef<marker::DormantMut, K, V, NodeType>, HandleType> {
879 Handle { node: self.node.dormant(), idx: self.idx, _marker: PhantomData }
880 }
881}
882
883impl<K, V, NodeType, HandleType> Handle<NodeRef<marker::DormantMut, K, V, NodeType>, HandleType> {
884 pub(super) unsafe fn awaken<'a>(
891 self,
892 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
893 Handle { node: unsafe { self.node.awaken() }, idx: self.idx, _marker: PhantomData }
895 }
896}
897
898impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
899 pub(super) unsafe fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
902 debug_assert!(idx <= node.len());
903
904 Handle { node, idx, _marker: PhantomData }
905 }
906
907 pub(super) fn left_kv(
908 self,
909 ) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
910 if self.idx > 0 {
911 Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) })
913 } else {
914 Err(self)
915 }
916 }
917
918 pub(super) fn right_kv(
919 self,
920 ) -> Result<Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV>, Self> {
921 if self.idx < self.node.len() {
922 Ok(unsafe { Handle::new_kv(self.node, self.idx) })
924 } else {
925 Err(self)
926 }
927 }
928}
929
930pub(super) enum LeftOrRight<T> {
931 Left(T),
932 Right(T),
933}
934
935fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight<usize>) {
941 debug_assert!(edge_idx <= CAPACITY);
942 match edge_idx {
944 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)),
945 EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)),
946 EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)),
947 _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))),
948 }
949}
950
951impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
952 unsafe fn insert_fit(
956 mut self,
957 key: K,
958 val: V,
959 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
960 debug_assert!(self.node.len() < CAPACITY);
961 let new_len = self.node.len() + 1;
962
963 unsafe {
965 slice_insert(self.node.key_area_mut(..new_len), self.idx, key);
966 slice_insert(self.node.val_area_mut(..new_len), self.idx, val);
967 *self.node.len_mut() = new_len as u16;
968
969 Handle::new_kv(self.node, self.idx)
970 }
971 }
972}
973
974impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
975 fn insert<A: AllocatorClone>(
981 self,
982 key: K,
983 val: V,
984 alloc: A,
985 ) -> (
986 Option<SplitResult<'a, K, V, marker::Leaf>>,
987 Handle<NodeRef<marker::DormantMut, K, V, marker::Leaf>, marker::KV>,
988 ) {
989 if self.node.len() < CAPACITY {
990 let handle = unsafe { self.insert_fit(key, val) };
992 (None, handle.dormant())
993 } else {
994 let (middle_kv_idx, insertion) = splitpoint(self.idx);
995 let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
997 let mut result = middle.split(alloc);
998 let insertion_edge = match insertion {
999 LeftOrRight::Left(insert_idx) => unsafe {
1001 Handle::new_edge(result.left.reborrow_mut(), insert_idx)
1002 },
1003 LeftOrRight::Right(insert_idx) => unsafe {
1005 Handle::new_edge(result.right.borrow_mut(), insert_idx)
1006 },
1007 };
1008 let handle = unsafe { insertion_edge.insert_fit(key, val).dormant() };
1011 (Some(result), handle)
1012 }
1013 }
1014}
1015
1016impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1017 fn correct_parent_link(self) {
1020 let ptr = unsafe { NonNull::new_unchecked(NodeRef::as_internal_ptr(&self.node)) };
1023 let idx = self.idx;
1024 let mut child = self.descend();
1025 child.set_parent_link(ptr, idx);
1026 }
1027}
1028
1029impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
1030 fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
1034 debug_assert!(self.node.len() < CAPACITY);
1035 debug_assert!(edge.height == self.node.height - 1);
1036 let new_len = self.node.len() + 1;
1037
1038 unsafe {
1040 slice_insert(self.node.key_area_mut(..new_len), self.idx, key);
1041 slice_insert(self.node.val_area_mut(..new_len), self.idx, val);
1042 slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node);
1043 *self.node.len_mut() = new_len as u16;
1044
1045 self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1);
1046 }
1047 }
1048
1049 fn insert<A: AllocatorClone>(
1053 mut self,
1054 key: K,
1055 val: V,
1056 edge: Root<K, V>,
1057 alloc: A,
1058 ) -> Option<SplitResult<'a, K, V, marker::Internal>> {
1059 assert!(edge.height == self.node.height - 1);
1060
1061 if self.node.len() < CAPACITY {
1062 self.insert_fit(key, val, edge);
1063 None
1064 } else {
1065 let (middle_kv_idx, insertion) = splitpoint(self.idx);
1066 let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) };
1068 let mut result = middle.split(alloc);
1069 let mut insertion_edge = match insertion {
1070 LeftOrRight::Left(insert_idx) => unsafe {
1072 Handle::new_edge(result.left.reborrow_mut(), insert_idx)
1073 },
1074 LeftOrRight::Right(insert_idx) => unsafe {
1076 Handle::new_edge(result.right.borrow_mut(), insert_idx)
1077 },
1078 };
1079 insertion_edge.insert_fit(key, val, edge);
1080 Some(result)
1081 }
1082 }
1083}
1084
1085impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
1086 pub(super) fn insert_recursing<A: AllocatorClone>(
1094 self,
1095 key: K,
1096 value: V,
1097 alloc: A,
1098 split_root: impl FnOnce(SplitResult<'a, K, V, marker::LeafOrInternal>),
1099 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1100 let (mut split, handle) = match self.insert(key, value, alloc.clone()) {
1101 (None, handle) => return unsafe { handle.awaken() },
1104 (Some(split), handle) => (split.forget_node_type(), handle),
1105 };
1106
1107 loop {
1108 split = match split.left.ascend() {
1109 Ok(parent) => {
1110 match parent.insert(split.kv.0, split.kv.1, split.right, alloc.clone()) {
1111 None => return unsafe { handle.awaken() },
1114 Some(split) => split.forget_node_type(),
1115 }
1116 }
1117 Err(root) => {
1118 split_root(SplitResult { left: root, ..split });
1119 return unsafe { handle.awaken() };
1122 }
1123 };
1124 }
1125 }
1126}
1127
1128impl<BorrowType: marker::BorrowType, K, V>
1129 Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge>
1130{
1131 pub(super) fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
1138 const {
1139 assert!(BorrowType::TRAVERSAL_PERMIT);
1140 }
1141
1142 let parent_ptr = NodeRef::as_internal_ptr(&self.node);
1150 let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() };
1152 NodeRef { node, height: self.node.height - 1, _marker: PhantomData }
1153 }
1154}
1155
1156impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Immut<'a>, K, V, NodeType>, marker::KV> {
1157 pub(super) fn into_kv(self) -> (&'a K, &'a V) {
1158 debug_assert!(self.idx < self.node.len());
1159 let leaf = self.node.into_leaf();
1160 let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() };
1162 let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() };
1164 (k, v)
1165 }
1166}
1167
1168impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1169 pub(super) fn key_mut(&mut self) -> &mut K {
1170 unsafe { self.node.key_area_mut(self.idx).assume_init_mut() }
1172 }
1173
1174 pub(super) fn into_val_mut(self) -> &'a mut V {
1175 debug_assert!(self.idx < self.node.len());
1176 let leaf = self.node.into_leaf_mut();
1177 unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() }
1179 }
1180
1181 pub(super) fn into_kv_mut(self) -> (&'a mut K, &'a mut V) {
1182 debug_assert!(self.idx < self.node.len());
1183 let leaf = self.node.into_leaf_mut();
1184 let k = unsafe { leaf.keys.get_unchecked_mut(self.idx).assume_init_mut() };
1186 let v = unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() };
1188 (k, v)
1189 }
1190}
1191
1192impl<'a, K, V, NodeType> Handle<NodeRef<marker::ValMut<'a>, K, V, NodeType>, marker::KV> {
1193 pub(super) fn into_kv_valmut(self) -> (&'a K, &'a mut V) {
1194 unsafe { self.node.into_key_val_mut_at(self.idx) }
1196 }
1197}
1198
1199impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1200 pub(super) fn kv_mut(&mut self) -> (&mut K, &mut V) {
1201 debug_assert!(self.idx < self.node.len());
1202 unsafe {
1206 let leaf = self.node.as_leaf_mut();
1207 let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut();
1208 let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut();
1209 (key, val)
1210 }
1211 }
1212
1213 pub(super) fn replace_kv(&mut self, k: K, v: V) -> (K, V) {
1215 let (key, val) = self.kv_mut();
1216 (mem::replace(key, k), mem::replace(val, v))
1217 }
1218}
1219
1220impl<K, V, NodeType> Handle<NodeRef<marker::Dying, K, V, NodeType>, marker::KV> {
1221 pub(super) unsafe fn into_key_val(mut self) -> (K, V) {
1225 debug_assert!(self.idx < self.node.len());
1226 let leaf = self.node.as_leaf_dying();
1227 unsafe {
1229 let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_read();
1230 let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_read();
1231 (key, val)
1232 }
1233 }
1234
1235 #[inline]
1239 pub(super) unsafe fn drop_key_val(mut self) {
1240 struct Dropper<'a, T>(&'a mut MaybeUninit<T>);
1242 impl<T> Drop for Dropper<'_, T> {
1243 #[inline]
1244 fn drop(&mut self) {
1245 unsafe {
1247 self.0.assume_init_drop();
1248 }
1249 }
1250 }
1251
1252 debug_assert!(self.idx < self.node.len());
1253 let leaf = self.node.as_leaf_dying();
1254 unsafe {
1256 let key = leaf.keys.get_unchecked_mut(self.idx);
1257 let val = leaf.vals.get_unchecked_mut(self.idx);
1258 let _guard = Dropper(val);
1259 key.assume_init_drop();
1260 }
1262 }
1263}
1264
1265impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
1266 fn split_leaf_data(&mut self, new_node: &mut LeafNode<K, V>) -> (K, V) {
1269 debug_assert!(self.idx < self.node.len());
1270 let old_len = self.node.len();
1271 let new_len = old_len - self.idx - 1;
1272 new_node.len = new_len as u16;
1273 unsafe {
1275 let k = self.node.key_area_mut(self.idx).assume_init_read();
1276 let v = self.node.val_area_mut(self.idx).assume_init_read();
1277
1278 move_to_slice(
1279 self.node.key_area_mut(self.idx + 1..old_len),
1280 &mut new_node.keys[..new_len],
1281 );
1282 move_to_slice(
1283 self.node.val_area_mut(self.idx + 1..old_len),
1284 &mut new_node.vals[..new_len],
1285 );
1286
1287 *self.node.len_mut() = self.idx as u16;
1288 (k, v)
1289 }
1290 }
1291}
1292
1293impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
1294 pub(super) fn split<A: AllocatorClone>(
1302 mut self,
1303 alloc: A,
1304 ) -> SplitResult<'a, K, V, marker::Leaf> {
1305 let mut new_node = LeafNode::new(alloc);
1306
1307 let kv = self.split_leaf_data(&mut new_node);
1308
1309 let right = NodeRef::from_new_leaf(new_node);
1310 SplitResult { left: self.node, kv, right }
1311 }
1312
1313 pub(super) fn remove(
1316 mut self,
1317 ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
1318 let old_len = self.node.len();
1319 unsafe {
1321 let k = slice_remove(self.node.key_area_mut(..old_len), self.idx);
1322 let v = slice_remove(self.node.val_area_mut(..old_len), self.idx);
1323 *self.node.len_mut() = (old_len - 1) as u16;
1324 ((k, v), self.left_edge())
1325 }
1326 }
1327}
1328
1329impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1330 pub(super) fn split<A: AllocatorClone>(
1338 mut self,
1339 alloc: A,
1340 ) -> SplitResult<'a, K, V, marker::Internal> {
1341 let old_len = self.node.len();
1342 unsafe {
1344 let mut new_node = InternalNode::new(alloc);
1345 let kv = self.split_leaf_data(&mut new_node.data);
1346 let new_len = usize::from(new_node.data.len);
1347 move_to_slice(
1348 self.node.edge_area_mut(self.idx + 1..old_len + 1),
1349 &mut new_node.edges[..new_len + 1],
1350 );
1351
1352 let height = NonZero::new_unchecked(self.node.height);
1354 let right = NodeRef::from_new_internal(new_node, height);
1355
1356 SplitResult { left: self.node, kv, right }
1357 }
1358 }
1359}
1360
1361pub(super) struct BalancingContext<'a, K, V> {
1364 parent: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV>,
1365 left_child: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1366 right_child: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1367}
1368
1369impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
1370 pub(super) fn consider_for_balancing(self) -> BalancingContext<'a, K, V> {
1371 let self1 = unsafe { ptr::read(&self) };
1373 let self2 = unsafe { ptr::read(&self) };
1375 BalancingContext {
1376 parent: self,
1377 left_child: self1.left_edge().descend(),
1378 right_child: self2.right_edge().descend(),
1379 }
1380 }
1381}
1382
1383impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1384 pub(super) fn choose_parent_kv(self) -> Result<LeftOrRight<BalancingContext<'a, K, V>>, Self> {
1399 match unsafe { ptr::read(&self) }.ascend() {
1401 Ok(parent_edge) => match parent_edge.left_kv() {
1402 Ok(left_parent_kv) => Ok(LeftOrRight::Left(BalancingContext {
1403 parent: unsafe { ptr::read(&left_parent_kv) },
1405 left_child: left_parent_kv.left_edge().descend(),
1406 right_child: self,
1407 })),
1408 Err(parent_edge) => match parent_edge.right_kv() {
1409 Ok(right_parent_kv) => Ok(LeftOrRight::Right(BalancingContext {
1410 parent: unsafe { ptr::read(&right_parent_kv) },
1412 left_child: self,
1413 right_child: right_parent_kv.right_edge().descend(),
1414 })),
1415 Err(_) => unreachable!("empty internal node"),
1416 },
1417 },
1418 Err(root) => Err(root),
1419 }
1420 }
1421}
1422
1423impl<'a, K, V> BalancingContext<'a, K, V> {
1424 pub(super) fn left_child_len(&self) -> usize {
1425 self.left_child.len()
1426 }
1427
1428 pub(super) fn right_child_len(&self) -> usize {
1429 self.right_child.len()
1430 }
1431
1432 pub(super) fn into_left_child(self) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1433 self.left_child
1434 }
1435
1436 pub(super) fn into_right_child(self) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1437 self.right_child
1438 }
1439
1440 pub(super) fn can_merge(&self) -> bool {
1443 self.left_child.len() + 1 + self.right_child.len() <= CAPACITY
1444 }
1445}
1446
1447impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> {
1448 fn do_merge<
1450 F: FnOnce(
1451 NodeRef<marker::Mut<'a>, K, V, marker::Internal>,
1452 NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1453 ) -> R,
1454 R,
1455 A: Allocator,
1456 >(
1457 self,
1458 result: F,
1459 alloc: A,
1460 ) -> R {
1461 let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent;
1462 let old_parent_len = parent_node.len();
1463 let mut left_node = self.left_child;
1464 let old_left_len = left_node.len();
1465 let mut right_node = self.right_child;
1466 let right_len = right_node.len();
1467 let new_left_len = old_left_len + 1 + right_len;
1468
1469 assert!(new_left_len <= CAPACITY);
1470
1471 unsafe {
1473 *left_node.len_mut() = new_left_len as u16;
1474
1475 let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx);
1476 left_node.key_area_mut(old_left_len).write(parent_key);
1477 move_to_slice(
1478 right_node.key_area_mut(..right_len),
1479 left_node.key_area_mut(old_left_len + 1..new_left_len),
1480 );
1481
1482 let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx);
1483 left_node.val_area_mut(old_left_len).write(parent_val);
1484 move_to_slice(
1485 right_node.val_area_mut(..right_len),
1486 left_node.val_area_mut(old_left_len + 1..new_left_len),
1487 );
1488
1489 slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1);
1490 parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len);
1491 *parent_node.len_mut() -= 1;
1492
1493 if parent_node.height > 1 {
1494 let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked();
1497 let mut right_node = right_node.cast_to_internal_unchecked();
1498 move_to_slice(
1499 right_node.edge_area_mut(..right_len + 1),
1500 left_node.edge_area_mut(old_left_len + 1..new_left_len + 1),
1501 );
1502
1503 left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1);
1504
1505 alloc.deallocate(right_node.node.cast(), Layout::new::<InternalNode<K, V>>());
1506 } else {
1507 alloc.deallocate(right_node.node.cast(), Layout::new::<LeafNode<K, V>>());
1508 }
1509 }
1510 result(parent_node, left_node)
1511 }
1512
1513 pub(super) fn merge_tracking_parent<A: AllocatorClone>(
1518 self,
1519 alloc: A,
1520 ) -> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
1521 self.do_merge(|parent, _child| parent, alloc)
1522 }
1523
1524 pub(super) fn merge_tracking_child<A: AllocatorClone>(
1529 self,
1530 alloc: A,
1531 ) -> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
1532 self.do_merge(|_parent, child| child, alloc)
1533 }
1534
1535 pub(super) fn merge_tracking_child_edge<A: AllocatorClone>(
1541 self,
1542 track_edge_idx: LeftOrRight<usize>,
1543 alloc: A,
1544 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1545 let old_left_len = self.left_child.len();
1546 let right_len = self.right_child.len();
1547 assert!(match track_edge_idx {
1548 LeftOrRight::Left(idx) => idx <= old_left_len,
1549 LeftOrRight::Right(idx) => idx <= right_len,
1550 });
1551 let child = self.merge_tracking_child(alloc);
1552 let new_idx = match track_edge_idx {
1553 LeftOrRight::Left(idx) => idx,
1554 LeftOrRight::Right(idx) => old_left_len + 1 + idx,
1555 };
1556 unsafe { Handle::new_edge(child, new_idx) }
1558 }
1559
1560 pub(super) fn steal_left(
1565 mut self,
1566 track_right_edge_idx: usize,
1567 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1568 self.bulk_steal_left(1);
1569 unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) }
1571 }
1572
1573 pub(super) fn steal_right(
1578 mut self,
1579 track_left_edge_idx: usize,
1580 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1581 self.bulk_steal_right(1);
1582 unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) }
1584 }
1585
1586 pub(super) fn bulk_steal_left(&mut self, count: usize) {
1588 assert!(count > 0);
1589 unsafe {
1591 let left_node = &mut self.left_child;
1592 let old_left_len = left_node.len();
1593 let right_node = &mut self.right_child;
1594 let old_right_len = right_node.len();
1595
1596 assert!(old_right_len + count <= CAPACITY);
1598 assert!(old_left_len >= count);
1599
1600 let new_left_len = old_left_len - count;
1601 let new_right_len = old_right_len + count;
1602 *left_node.len_mut() = new_left_len as u16;
1603 *right_node.len_mut() = new_right_len as u16;
1604
1605 {
1607 slice_shr(right_node.key_area_mut(..new_right_len), count);
1609 slice_shr(right_node.val_area_mut(..new_right_len), count);
1610
1611 move_to_slice(
1613 left_node.key_area_mut(new_left_len + 1..old_left_len),
1614 right_node.key_area_mut(..count - 1),
1615 );
1616 move_to_slice(
1617 left_node.val_area_mut(new_left_len + 1..old_left_len),
1618 right_node.val_area_mut(..count - 1),
1619 );
1620
1621 let k = left_node.key_area_mut(new_left_len).assume_init_read();
1623 let v = left_node.val_area_mut(new_left_len).assume_init_read();
1624 let (k, v) = self.parent.replace_kv(k, v);
1625
1626 right_node.key_area_mut(count - 1).write(k);
1628 right_node.val_area_mut(count - 1).write(v);
1629 }
1630
1631 match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) {
1632 (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1633 slice_shr(right.edge_area_mut(..new_right_len + 1), count);
1635
1636 move_to_slice(
1638 left.edge_area_mut(new_left_len + 1..old_left_len + 1),
1639 right.edge_area_mut(..count),
1640 );
1641
1642 right.correct_childrens_parent_links(0..new_right_len + 1);
1643 }
1644 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1645 _ => unreachable!(),
1646 }
1647 }
1648 }
1649
1650 pub(super) fn bulk_steal_right(&mut self, count: usize) {
1652 assert!(count > 0);
1653 unsafe {
1655 let left_node = &mut self.left_child;
1656 let old_left_len = left_node.len();
1657 let right_node = &mut self.right_child;
1658 let old_right_len = right_node.len();
1659
1660 assert!(old_left_len + count <= CAPACITY);
1662 assert!(old_right_len >= count);
1663
1664 let new_left_len = old_left_len + count;
1665 let new_right_len = old_right_len - count;
1666 *left_node.len_mut() = new_left_len as u16;
1667 *right_node.len_mut() = new_right_len as u16;
1668
1669 {
1671 let k = right_node.key_area_mut(count - 1).assume_init_read();
1673 let v = right_node.val_area_mut(count - 1).assume_init_read();
1674 let (k, v) = self.parent.replace_kv(k, v);
1675
1676 left_node.key_area_mut(old_left_len).write(k);
1678 left_node.val_area_mut(old_left_len).write(v);
1679
1680 move_to_slice(
1682 right_node.key_area_mut(..count - 1),
1683 left_node.key_area_mut(old_left_len + 1..new_left_len),
1684 );
1685 move_to_slice(
1686 right_node.val_area_mut(..count - 1),
1687 left_node.val_area_mut(old_left_len + 1..new_left_len),
1688 );
1689
1690 slice_shl(right_node.key_area_mut(..old_right_len), count);
1692 slice_shl(right_node.val_area_mut(..old_right_len), count);
1693 }
1694
1695 match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) {
1696 (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1697 move_to_slice(
1699 right.edge_area_mut(..count),
1700 left.edge_area_mut(old_left_len + 1..new_left_len + 1),
1701 );
1702
1703 slice_shl(right.edge_area_mut(..old_right_len + 1), count);
1705
1706 left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1);
1707 right.correct_childrens_parent_links(0..new_right_len + 1);
1708 }
1709 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1710 _ => unreachable!(),
1711 }
1712 }
1713 }
1714}
1715
1716impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1717 pub(super) fn forget_node_type(
1718 self,
1719 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1720 unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1722 }
1723}
1724
1725impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
1726 pub(super) fn forget_node_type(
1727 self,
1728 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::Edge> {
1729 unsafe { Handle::new_edge(self.node.forget_type(), self.idx) }
1731 }
1732}
1733
1734impl<BorrowType, K, V> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::KV> {
1735 pub(super) fn forget_node_type(
1736 self,
1737 ) -> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, marker::KV> {
1738 unsafe { Handle::new_kv(self.node.forget_type(), self.idx) }
1740 }
1741}
1742
1743impl<BorrowType, K, V, Type> Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, Type> {
1744 pub(super) fn force(
1746 self,
1747 ) -> ForceResult<
1748 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, Type>,
1749 Handle<NodeRef<BorrowType, K, V, marker::Internal>, Type>,
1750 > {
1751 match self.node.force() {
1752 ForceResult::Leaf(node) => {
1753 ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData })
1754 }
1755 ForceResult::Internal(node) => {
1756 ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData })
1757 }
1758 }
1759 }
1760}
1761
1762impl<'a, K, V, Type> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, Type> {
1763 pub(super) unsafe fn cast_to_leaf_unchecked(
1765 self,
1766 ) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, Type> {
1767 let node = unsafe { self.node.cast_to_leaf_unchecked() };
1769 Handle { node, idx: self.idx, _marker: PhantomData }
1770 }
1771}
1772
1773impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::Edge> {
1774 pub(super) fn move_suffix(
1777 &mut self,
1778 right: &mut NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>,
1779 ) {
1780 unsafe {
1782 let new_left_len = self.idx;
1783 let mut left_node = self.reborrow_mut().into_node();
1784 let old_left_len = left_node.len();
1785
1786 let new_right_len = old_left_len - new_left_len;
1787 let mut right_node = right.reborrow_mut();
1788
1789 assert!(right_node.len() == 0);
1790 assert!(left_node.height == right_node.height);
1791
1792 if new_right_len > 0 {
1793 *left_node.len_mut() = new_left_len as u16;
1794 *right_node.len_mut() = new_right_len as u16;
1795
1796 move_to_slice(
1797 left_node.key_area_mut(new_left_len..old_left_len),
1798 right_node.key_area_mut(..new_right_len),
1799 );
1800 move_to_slice(
1801 left_node.val_area_mut(new_left_len..old_left_len),
1802 right_node.val_area_mut(..new_right_len),
1803 );
1804 match (left_node.force(), right_node.force()) {
1805 (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => {
1806 move_to_slice(
1807 left.edge_area_mut(new_left_len + 1..old_left_len + 1),
1808 right.edge_area_mut(1..new_right_len + 1),
1809 );
1810 right.correct_childrens_parent_links(1..new_right_len + 1);
1811 }
1812 (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {}
1813 _ => unreachable!(),
1814 }
1815 }
1816 }
1817 }
1818}
1819
1820pub(super) enum ForceResult<Leaf, Internal> {
1821 Leaf(Leaf),
1822 Internal(Internal),
1823}
1824
1825pub(super) struct SplitResult<'a, K, V, NodeType> {
1827 pub left: NodeRef<marker::Mut<'a>, K, V, NodeType>,
1829 pub kv: (K, V),
1831 pub right: NodeRef<marker::Owned, K, V, NodeType>,
1833}
1834
1835impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> {
1836 pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> {
1837 SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() }
1838 }
1839}
1840
1841impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> {
1842 pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> {
1843 SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() }
1844 }
1845}
1846
1847pub(super) mod marker {
1848 use core::marker::PhantomData;
1849
1850 pub(crate) enum Leaf {}
1851 pub(crate) enum Internal {}
1852 pub(crate) enum LeafOrInternal {}
1853
1854 pub(crate) enum Owned {}
1855 pub(crate) enum Dying {}
1856 pub(crate) enum DormantMut {}
1857 pub(crate) struct Immut<'a>(PhantomData<&'a ()>);
1858 pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>);
1859 pub(crate) struct ValMut<'a>(PhantomData<&'a mut ()>);
1860
1861 pub(crate) trait BorrowType {
1862 const TRAVERSAL_PERMIT: bool = true;
1866 }
1867 impl BorrowType for Owned {
1868 const TRAVERSAL_PERMIT: bool = false;
1873 }
1874 impl BorrowType for Dying {}
1875 impl<'a> BorrowType for Immut<'a> {}
1876 impl<'a> BorrowType for Mut<'a> {}
1877 impl<'a> BorrowType for ValMut<'a> {}
1878 impl BorrowType for DormantMut {}
1879
1880 pub(crate) enum KV {}
1881 pub(crate) enum Edge {}
1882}
1883
1884unsafe fn slice_insert<T>(slice: &mut [MaybeUninit<T>], idx: usize, val: T) {
1889 let len = slice.len();
1890 debug_assert!(len > idx);
1891 let slice_ptr = slice.as_mut_ptr();
1892 unsafe {
1894 if len > idx + 1 {
1895 ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1);
1896 }
1897 (*slice_ptr.add(idx)).write(val);
1898 }
1899}
1900
1901unsafe fn slice_remove<T>(slice: &mut [MaybeUninit<T>], idx: usize) -> T {
1907 let len = slice.len();
1908 debug_assert!(idx < len);
1909 let slice_ptr = slice.as_mut_ptr();
1910 unsafe {
1912 let ret = (*slice_ptr.add(idx)).assume_init_read();
1913 ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1);
1914 ret
1915 }
1916}
1917
1918unsafe fn slice_shl<T>(slice: &mut [MaybeUninit<T>], distance: usize) {
1923 let slice_ptr = slice.as_mut_ptr();
1924 unsafe {
1926 ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance);
1927 }
1928}
1929
1930unsafe fn slice_shr<T>(slice: &mut [MaybeUninit<T>], distance: usize) {
1935 let slice_ptr = slice.as_mut_ptr();
1936 unsafe {
1938 ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance);
1939 }
1940}
1941
1942fn move_to_slice<T>(src: &mut [MaybeUninit<T>], dst: &mut [MaybeUninit<T>]) {
1946 assert!(src.len() == dst.len());
1947 unsafe {
1949 ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());
1950 }
1951}
1952
1953#[cfg(test)]
1954mod tests;