1#![allow(rustdoc::redundant_explicit_links)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(docsrs, allow(unused_attributes))]
4#![cfg_attr(not(feature = "std"), no_std)]
5extern crate alloc;
164#[cfg(any(feature = "std", test))]
165extern crate std;
166
167mod entry;
168mod iter;
169pub use entry::*;
170pub use iter::*;
171#[cfg(test)]
172mod tests;
173
174use alloc::vec::Vec;
175use core::marker::PhantomData;
176use core::{
177 borrow::Borrow,
178 cmp::{Ordering, PartialEq},
179 fmt, mem,
180 ops::Deref,
181 ptr::{NonNull, null_mut},
182};
183use pointers::{CloneablePointer, Pointer};
184
185pub unsafe trait AvlItem<Tag>: Sized {
272 fn get_node(&self) -> &mut AvlNode<Self, Tag>;
273}
274
275#[macro_export]
281macro_rules! impl_ord_with_borrow {
282 ($cls: ty, $key_type: ty) => {
283 impl PartialOrd for $cls {
284 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
285 Some(Ord::cmp(self, other))
286 }
287 }
288 impl PartialEq for $cls {
289 fn eq(&self, other: &Self) -> bool {
290 Borrow::<$key_type>::borrow(self) == Borrow::<$key_type>::borrow(other)
291 }
292 }
293 impl Eq for $cls {}
294
295 impl Ord for $cls {
296 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
297 Borrow::<$key_type>::borrow(self).cmp(Borrow::<$key_type>::borrow(other))
298 }
299 }
300 };
301}
302
303#[macro_export(local_inner_macros)]
305macro_rules! trace_log {
306 ($($arg:tt)+)=>{
307 #[cfg(feature="trace_log")]
308 {
309 log::debug!($($arg)+);
310 }
311 };
312}
313
314pub(crate) const DIR_LEFT: Dir = Dir(false);
315pub(crate) const DIR_RIGHT: Dir = Dir(true);
316
317#[derive(PartialEq, Debug, Copy, Clone)]
318pub(crate) struct Dir(bool);
319
320impl Dir {
321 #[inline(always)]
322 const fn to_usize(&self) -> usize {
323 self.0 as usize
324 }
325
326 #[inline(always)]
327 const fn reverse(&self) -> Self {
328 Self(!self.0)
329 }
330
331 #[inline(always)]
332 fn to_balance(&self) -> i8 {
333 if *self == DIR_LEFT { -1 } else { 1 }
334 }
335}
336
337impl From<i8> for Dir {
338 #[inline(always)]
339 fn from(i: i8) -> Self {
340 Self(i != 0)
341 }
342}
343
344impl From<bool> for Dir {
345 #[inline(always)]
346 fn from(i: bool) -> Self {
347 Self(i)
348 }
349}
350
351macro_rules! balance_to_child {
352 ($balance: expr) => {{ ($balance > 1).into() }};
353}
354
355pub struct AvlNode<T: AvlItem<Tag>, Tag> {
356 pub parent: *mut T,
357 pub children: [*mut T; 2],
358 pub balance: i8,
359 _phan: PhantomData<fn(&Tag)>,
360}
361
362unsafe impl<T: AvlItem<Tag> + Send, Tag> Send for AvlNode<T, Tag> {}
363
364impl<T: AvlItem<Tag>, Tag> AvlNode<T, Tag> {
365 #[inline(always)]
366 pub fn detach(&mut self) {
367 self.children = [null_mut(), null_mut()];
368 self.parent = null_mut();
369 self.balance = 0;
370 }
371
372 #[inline(always)]
373 fn get_child(&self, dir: Dir) -> *mut T {
374 unsafe { *self.children.get_unchecked(dir.to_usize()) }
375 }
376
377 #[inline(always)]
378 fn set_child(&mut self, dir: Dir, child: *mut T) {
379 self.children[dir.to_usize()] = child;
380 }
381
382 #[inline(always)]
383 fn left(&self) -> *mut T {
384 self.children[0]
385 }
386
387 #[inline(always)]
388 fn right(&self) -> *mut T {
389 self.children[1]
390 }
391
392 #[inline(always)]
397 fn set_child2<P: Pointer<Target = T>>(
398 &mut self, dir: Dir, child: *mut P::Target, parent: *mut P::Target,
399 ) {
400 if !child.is_null() {
401 unsafe { (*child).get_node().parent = parent };
402 }
403 self.set_child(dir, child);
404 }
405
406 #[inline(always)]
407 fn get_parent(&self) -> *mut T {
408 self.parent
409 }
410
411 #[inline(always)]
412 fn _child_direction(&self, child_p: *mut T) -> Dir {
413 let is_right = self.children[1] == child_p;
415 #[cfg(debug_assertions)]
416 {
417 if !is_right {
418 debug_assert!(self.children[0] == child_p);
419 }
420 }
421 is_right.into()
422 }
423
424 #[inline(always)]
425 fn child_direction(parent: *mut T, child_p: *mut T) -> Dir {
426 if !parent.is_null() {
427 unsafe { (*parent).get_node() }._child_direction(child_p)
428 } else {
429 DIR_LEFT
430 }
431 }
432
433 #[inline(always)]
434 fn parent_direction(node: *mut T) -> Dir {
435 let parent = unsafe { (*node).get_node() }.get_parent();
437 Self::child_direction(parent, node)
438 }
439
440 #[inline(always)]
442 pub fn swap(&mut self, other: &mut AvlNode<T, Tag>) {
443 mem::swap(self, other);
444 }
445}
446
447impl<T: AvlItem<Tag>, Tag> Default for AvlNode<T, Tag> {
448 fn default() -> Self {
449 Self {
450 children: [null_mut(), null_mut()],
451 parent: null_mut(),
452 balance: 0,
453 _phan: Default::default(),
454 }
455 }
456}
457
458#[allow(unused_must_use)]
459impl<T: AvlItem<Tag>, Tag> fmt::Debug for AvlNode<T, Tag> {
460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
461 write!(f, "(")?;
462 if !self.left().is_null() {
463 write!(f, "left: {:p}", self.left())?;
464 } else {
465 write!(f, "left: none ")?;
466 }
467
468 if !self.right().is_null() {
469 write!(f, "right: {:p}", self.right())?;
470 } else {
471 write!(f, "right: none ")?;
472 }
473 write!(f, ")")
474 }
475}
476
477pub struct AvlTree<P, Tag>
482where
483 P: Pointer,
484 P::Target: AvlItem<Tag>,
485{
486 root: *mut P::Target,
487 count: usize,
488 _phan: PhantomData<fn(P, &Tag)>,
489}
490
491impl<P, Tag> Default for AvlTree<P, Tag>
492where
493 P: Pointer + Send,
494 P::Target: AvlItem<Tag>,
495{
496 #[inline(always)]
497 fn default() -> Self {
498 Self::new()
499 }
500}
501
502unsafe impl<P, Tag> Send for AvlTree<P, Tag>
503where
504 P: Pointer + Send,
505 P::Target: AvlItem<Tag>,
506{
507}
508
509unsafe impl<P, Tag> Sync for AvlTree<P, Tag>
510where
511 P: Pointer + Send,
512 P::Target: AvlItem<Tag>,
513{
514}
515
516impl<P, Tag> fmt::Debug for AvlTree<P, Tag>
517where
518 P: Pointer,
519 P::Target: AvlItem<Tag> + fmt::Debug,
520{
521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522 let _ = write!(f, "AvlTree{{");
523 if self.count > 0 {
524 let mut iter = self.iter();
525 loop {
526 let node = iter.next().unwrap();
527 let _ = write!(f, "{:?}", node.as_ref().as_ref());
528 if iter.len() > 0 {
529 let _ = write!(f, ", ");
530 } else {
531 break;
532 }
533 }
534 }
535 write!(f, "}}")
536 }
537}
538
539impl<P, Tag> AvlTree<P, Tag>
540where
541 P: Pointer,
542 P::Target: AvlItem<Tag>,
543{
544 #[inline]
546 pub fn new() -> Self {
547 AvlTree { count: 0, root: null_mut(), _phan: Default::default() }
548 }
549
550 #[inline]
551 pub fn is_empty(&self) -> bool {
552 self.count == 0
553 }
554
555 #[inline]
556 pub fn len(&self) -> usize {
557 self.count
558 }
559
560 #[inline]
567 pub fn add(&mut self, node: P) -> Result<(), P>
568 where
569 P::Target: Ord,
570 {
571 if !self.root.is_null() {
572 let mut parent = self.root;
573 unsafe {
574 loop {
575 let dir = match node.as_ref().cmp((&*parent).as_ref()) {
577 Ordering::Greater => DIR_RIGHT,
578 Ordering::Less => DIR_LEFT,
579 Ordering::Equal => return Err(node),
580 };
581 let child = (*parent).get_node().get_child(dir);
582 if !child.is_null() {
583 parent = child;
584 } else {
585 self._insert(node.into_raw() as *mut P::Target, parent, dir);
586 return Ok(());
587 }
588 }
589 }
590 } else {
591 debug_assert_eq!(self.count, 0);
592 self.root = node.into_raw() as *mut P::Target;
593 self.count = 1;
594 Ok(())
595 }
596 }
597
598 #[inline]
600 pub fn remove_by_key<K>(&mut self, key: &K) -> Option<P>
601 where
602 P::Target: Borrow<K>,
603 K: Ord,
604 {
605 let _cmp = |_key: &&K, node: &P::Target| -> Ordering { _key.cmp(&node.borrow()) };
606 if let Entry::Occupied(ent) = self.entry_with::<&K, _>(key, _cmp) {
607 Some(ent.remove())
608 } else {
609 None
610 }
611 }
612
613 #[inline]
615 pub fn remove(&mut self, node: &P)
616 where
617 P::Target: Ord,
618 {
619 let _cmp = |_cur: &&P::Target, node: &P::Target| -> Ordering { _cur.cmp(&node.borrow()) };
620 if let Entry::Occupied(ent) = self.entry_with::<&P::Target, _>(node.as_ref(), _cmp) {
621 ent.remove();
622 }
623 }
624
625 #[inline]
628 pub fn entry<'a, K>(&'a mut self, key: K) -> Entry<'a, P, Tag, K>
629 where
630 P::Target: Borrow<K>,
631 K: Ord,
632 {
633 self.entry_with(key, |_key: &K, node: &P::Target| _key.cmp(node.borrow()))
634 }
635
636 #[inline]
638 pub fn entry_with<'a, K, F>(&'a mut self, key: K, cmp_f: F) -> Entry<'a, P, Tag, K>
639 where
640 F: Fn(&K, &P::Target) -> Ordering,
641 {
642 if !self.root.is_null() {
643 let mut parent = self.root;
644 loop {
645 let dir = match cmp_f(&key, unsafe { &*parent }.as_ref()) {
647 Ordering::Greater => DIR_RIGHT,
648 Ordering::Less => DIR_LEFT,
649 Ordering::Equal => {
650 return Entry::Occupied(OccupiedEntry {
651 node: unsafe { NonNull::new_unchecked(parent) },
652 tree: self,
653 });
654 }
655 };
656 let child = unsafe { (*parent).get_node() }.get_child(dir);
657 if !child.is_null() {
658 parent = child;
659 } else {
660 return Entry::Vacant(VacantEntry {
661 node: parent,
662 direction: dir,
663 tree: self,
664 key,
665 });
666 }
667 }
668 } else {
669 Entry::Vacant(VacantEntry { node: null_mut(), direction: DIR_RIGHT, tree: self, key })
670 }
671 }
672
673 #[inline]
674 pub fn get<'a, K>(&'a self, key: &K) -> Option<AvlNodeRef<'a, P>>
675 where
676 P::Target: Borrow<K>,
677 K: Ord,
678 {
679 self.get_with(|node| key.cmp(node.borrow()))
680 }
681
682 pub fn get_with<'a, F>(&'a self, cmp_f: F) -> Option<AvlNodeRef<'a, P>>
683 where
684 F: Fn(&P::Target) -> Ordering,
685 {
686 if !self.root.is_null() {
687 let mut node = self.root;
688 loop {
689 let dir = match cmp_f(unsafe { &*node }.as_ref()) {
691 Ordering::Greater => DIR_RIGHT,
692 Ordering::Less => DIR_LEFT,
693 Ordering::Equal => return Some(AvlNodeRef::new(node)),
694 };
695 let child = unsafe { (*node).get_node() }.get_child(dir);
696 if !child.is_null() {
697 node = child;
698 } else {
699 return None;
700 }
701 }
702 } else {
703 None
704 }
705 }
706
707 #[allow(clippy::not_unsafe_ptr_arg_deref)]
708 #[inline]
709 pub(crate) fn _insert(
710 &mut self,
711 new_ptr: *mut P::Target,
712 parent: *mut P::Target, mut which_child: Dir,
714 ) {
715 if !parent.is_null() {
716 let mut new_balance: i8;
717 unsafe { (*new_ptr).get_node() }.parent = parent;
718 let parent_node = unsafe { (*parent).get_node() };
719 parent_node.set_child(which_child, new_ptr);
720 self.count += 1;
721 let mut data: *mut P::Target = parent;
728 loop {
729 let node = unsafe { (*data).get_node() };
730 let old_balance = node.balance;
731 new_balance = old_balance + which_child.to_balance();
732 if new_balance == 0 {
733 node.balance = 0;
734 return;
735 }
736 if old_balance != 0 {
737 break;
738 }
739 node.balance = new_balance;
740 let parent_ptr = node.get_parent();
741 if parent_ptr.is_null() {
742 return;
743 }
744 which_child = unsafe { (*parent_ptr).get_node() }._child_direction(data);
745 data = parent_ptr;
746 }
747 self.rotate(data, new_balance);
748 } else {
749 debug_assert_eq!(self.count, 0);
750 self.root = new_ptr;
751 self.count += 1;
752 }
753 }
754
755 unsafe fn _insert_here(
764 &mut self, new_ptr: *mut P::Target, here: NonNull<P::Target>, direction: Dir,
765 ) {
766 crate::trace_log!("_insert_here {new_ptr:p} here {here:p} dir {direction:?}");
767 let mut dir_child = direction;
768 unsafe {
769 let child = here.as_ref().get_node().get_child(dir_child);
770 let parent;
771 if child.is_null() {
772 crate::trace_log!("direct at here {here:p}");
773 parent = here;
774 } else {
775 dir_child = dir_child.reverse();
776 parent = Self::bottom_child(NonNull::new_unchecked(child), dir_child);
777 crate::trace_log!("find bottom {parent:p}");
778 }
779 self._insert(new_ptr, parent.as_ptr(), dir_child);
780 }
781 }
782
783 #[inline]
784 fn rotate(&mut self, data: *mut P::Target, balance: i8) -> bool {
785 let dir: Dir = (balance >= 0).into();
788 let node = unsafe { (*data).get_node() };
789
790 let parent = node.get_parent();
791 let dir_inverse = dir.reverse();
792 let left_heavy = balance >> 1;
793 let right_heavy = -left_heavy;
794
795 let child = node.get_child(dir);
796 let child_node = unsafe { (*child).get_node() };
797 let mut child_balance = child_node.balance;
798
799 let which_child = AvlNode::<P::Target, Tag>::child_direction(parent, data);
800
801 if child_balance != right_heavy {
803 child_balance += right_heavy;
804
805 let c_right = child_node.get_child(dir_inverse);
806 node.set_child2::<P>(dir, c_right, data);
807 node.balance = -child_balance;
809
810 node.parent = child;
811 child_node.set_child(dir_inverse, data);
812 child_node.balance = child_balance;
815 if !parent.is_null() {
816 child_node.parent = parent;
817 unsafe { (*parent).get_node() }.set_child(which_child, child);
818 } else {
819 child_node.parent = null_mut();
820 self.root = child;
821 }
822 return child_balance == 0;
823 }
824 let g_child = child_node.get_child(dir_inverse);
828 let g_child_node = unsafe { (*g_child).get_node() };
829 let g_left = g_child_node.get_child(dir);
830 let g_right = g_child_node.get_child(dir_inverse);
831
832 node.set_child2::<P>(dir, g_right, data);
833 child_node.set_child2::<P>(dir_inverse, g_left, child);
834
835 let g_child_balance = g_child_node.balance;
842 if g_child_balance == right_heavy {
843 child_node.balance = left_heavy;
844 } else {
845 child_node.balance = 0;
846 }
847 child_node.parent = g_child;
848 g_child_node.set_child(dir, child);
849
850 if g_child_balance == left_heavy {
851 node.balance = right_heavy;
852 } else {
853 node.balance = 0;
854 }
855 g_child_node.balance = 0;
856
857 node.parent = g_child;
858 g_child_node.set_child(dir_inverse, data);
859
860 if !parent.is_null() {
861 g_child_node.parent = parent;
862 unsafe { (*parent).get_node() }.set_child(which_child, g_child);
863 } else {
864 g_child_node.parent = null_mut();
865 self.root = g_child;
866 }
867 true
868 }
869
870 pub(crate) unsafe fn _remove(&mut self, del: *mut P::Target) {
880 if self.count == 0 {
891 return;
892 }
893 if self.count == 1 && self.root == del {
894 self.root = null_mut();
895 self.count = 0;
896 unsafe { (*del).get_node().detach() };
897 return;
898 }
899 let mut which_child: Dir;
900
901 let del_node = unsafe { (*del).get_node() };
903
904 let node_swap_flag = !del_node.left().is_null() && !del_node.right().is_null();
905
906 if node_swap_flag {
907 let dir: Dir = balance_to_child!(del_node.balance + 1);
908 let child_temp = del_node.get_child(dir);
909
910 let dir_inverse: Dir = dir.reverse();
911 let child =
912 Self::bottom_child(unsafe { NonNull::new_unchecked(child_temp) }, dir_inverse)
913 .as_ptr();
914
915 let dir_child_temp = if child == child_temp {
918 dir
919 } else {
920 AvlNode::<P::Target, Tag>::parent_direction(child)
921 };
922
923 let parent = del_node.get_parent();
926 let dir_child_del = AvlNode::<P::Target, Tag>::child_direction(parent, del);
927
928 let child_node = unsafe { (*child).get_node() };
929 child_node.swap(del_node);
930
931 if child_node.get_child(dir) == child {
933 child_node.set_child(dir, del);
935 }
936
937 let c_dir = child_node.get_child(dir);
938 if c_dir == del {
939 del_node.parent = child;
940 } else if !c_dir.is_null() {
941 unsafe { (*c_dir).get_node() }.parent = child;
942 }
943
944 let c_inv = child_node.get_child(dir_inverse);
945 if c_inv == del {
946 del_node.parent = child;
947 } else if !c_inv.is_null() {
948 unsafe { (*c_inv).get_node() }.parent = child;
949 }
950
951 let parent = child_node.get_parent();
952 if !parent.is_null() {
953 unsafe { (*parent).get_node() }.set_child(dir_child_del, child);
954 } else {
955 self.root = child;
956 }
957
958 let parent = del_node.get_parent();
961 unsafe { (*parent).get_node() }.set_child(dir_child_temp, del);
962 which_child = Dir(!del_node.right().is_null());
964 let child = del_node.get_child(which_child);
965 if !child.is_null() {
966 unsafe { (*child).get_node() }.parent = del;
967 }
968 which_child = dir_child_temp;
969 } else {
970 let parent = del_node.get_parent();
971 which_child = AvlNode::<P::Target, Tag>::child_direction(parent, del);
972 }
973
974 let parent: *mut P::Target = del_node.get_parent();
977
978 let mut imm_data: *mut P::Target = del_node.left();
979 if !imm_data.is_null() {
980 let imm_node = unsafe { (*imm_data).get_node() };
981 imm_node.parent = parent;
982 } else {
983 imm_data = del_node.right();
984 if !imm_data.is_null() {
985 let imm_node = unsafe { (*imm_data).get_node() };
986 imm_node.parent = parent;
987 }
988 }
989 if !parent.is_null() {
992 assert!(self.count > 0);
993 self.count -= 1;
994
995 let parent_node = unsafe { (*parent).get_node() };
996 parent_node.set_child(which_child, imm_data);
997
998 let mut node_data: *mut P::Target = parent;
1001 loop {
1002 let node = unsafe { (*node_data).get_node() };
1006 let balance_delta = -which_child.to_balance();
1007 let old_balance = node.balance;
1008
1009 if old_balance == 0 {
1013 node.balance = balance_delta;
1014 break;
1015 }
1016 let new_balance = old_balance + balance_delta;
1017
1018 let parent = node.get_parent();
1019 which_child = AvlNode::<P::Target, Tag>::child_direction(parent, node_data);
1020
1021 if new_balance == 0 {
1027 node.balance = 0;
1028 } else if !self.rotate(node_data, new_balance) {
1029 break;
1030 }
1031
1032 if !parent.is_null() {
1033 node_data = parent;
1034 continue;
1035 }
1036 break;
1037 }
1038 } else if !imm_data.is_null() {
1039 debug_assert!(self.count > 0);
1040 self.count -= 1;
1041 self.root = imm_data;
1042 }
1043 if self.root.is_null() && self.count > 0 {
1044 panic!("AvlTree {} nodes left after remove but tree.root == nil", self.count);
1045 }
1046 del_node.detach();
1047 }
1048
1049 #[inline(always)]
1050 fn bottom_child(mut data: NonNull<P::Target>, dir: Dir) -> NonNull<P::Target> {
1051 loop {
1052 unsafe {
1053 let child = data.as_ref().get_node().get_child(dir);
1054 if !child.is_null() {
1055 data = NonNull::new_unchecked(child);
1056 } else {
1057 return data;
1058 }
1059 }
1060 }
1061 }
1062
1063 #[inline]
1067 pub fn iter(&self) -> AvlIter<'_, P, Tag> {
1068 let first_p = if !self.root.is_null() {
1069 Some(Self::bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_LEFT))
1070 } else {
1071 None
1072 };
1073 AvlIter::new(self, first_p, DIR_RIGHT)
1074 }
1075
1076 #[inline]
1080 pub fn iter_rev(&self) -> AvlIter<'_, P, Tag> {
1081 let last_p = if !self.root.is_null() {
1082 Some(Self::bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_RIGHT))
1083 } else {
1084 None
1085 };
1086 AvlIter::new(self, last_p, DIR_LEFT)
1087 }
1088
1089 #[inline]
1091 pub fn into_iter_rev(self) -> AvlIntoIter<P, Tag> {
1092 let node = self.root;
1093 core::mem::forget(self);
1094 AvlIntoIter::new(node, DIR_RIGHT)
1095 }
1096
1097 #[inline]
1098 pub fn prev<'a>(&'a self, data: &'a P::Target) -> Option<AvlNodeRef<'a, P>> {
1099 Self::_walk_dir(data.into(), DIR_LEFT).map(|p| AvlNodeRef::new(p.as_ptr()))
1100 }
1101
1102 #[inline]
1103 pub fn next<'a>(&'a self, data: &'a P::Target) -> Option<AvlNodeRef<'a, P>> {
1104 Self::_walk_dir(data.into(), DIR_RIGHT).map(|p| AvlNodeRef::new(p.as_ptr()))
1105 }
1106
1107 fn _walk_dir(mut data_ptr: NonNull<P::Target>, dir: Dir) -> Option<NonNull<P::Target>> {
1108 let dir_inverse = dir.reverse();
1109 let node = unsafe { data_ptr.as_ref().get_node() };
1110 let temp = node.get_child(dir);
1111 if !temp.is_null() {
1112 unsafe { Some(Self::bottom_child(NonNull::new_unchecked(temp), dir_inverse)) }
1113 } else {
1114 let mut parent = node.parent;
1115 while !parent.is_null() {
1116 let pdir = AvlNode::<P::Target, Tag>::child_direction(parent, data_ptr.as_ptr());
1117 if pdir == dir_inverse {
1118 return Some(unsafe { NonNull::new_unchecked(parent) });
1119 }
1120 let data_ptr_raw = parent;
1122 unsafe {
1123 parent = (*parent).get_node().parent;
1124 data_ptr = NonNull::new_unchecked(data_ptr_raw);
1125 }
1126 }
1127 debug_assert!(parent.is_null());
1129 None
1130 }
1131 }
1132
1133 #[inline]
1134 pub fn first<'a>(&'a self) -> Option<AvlNodeRef<'a, P>> {
1135 if !self.root.is_null() {
1136 let p = Self::bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_LEFT);
1137 Some(AvlNodeRef::<'a, P>::new(p.as_ptr()))
1138 } else {
1139 None
1140 }
1141 }
1142
1143 #[inline]
1144 pub fn last<'a>(&'a self) -> Option<AvlNodeRef<'a, P>> {
1145 if !self.root.is_null() {
1146 let p = Self::bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_RIGHT);
1147 Some(AvlNodeRef::<'a, P>::new(p.as_ptr()))
1148 } else {
1149 None
1150 }
1151 }
1152
1153 #[inline]
1157 pub fn first_entry<'a>(&'a mut self) -> Entry<'a, P, Tag, First> {
1158 if !self.root.is_null() {
1159 let p = Self::bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_LEFT);
1160 Entry::Occupied(OccupiedEntry { node: p, tree: self })
1161 } else {
1162 Entry::Vacant(VacantEntry {
1163 node: null_mut(),
1164 tree: self,
1165 direction: DIR_LEFT,
1166 key: First(),
1167 })
1168 }
1169 }
1170
1171 #[inline]
1175 pub fn last_entry<'a>(&'a mut self) -> Entry<'a, P, Tag, Last> {
1176 if !self.root.is_null() {
1177 let p = Self::bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_RIGHT);
1178 Entry::Occupied(OccupiedEntry { node: p, tree: self })
1179 } else {
1180 Entry::Vacant(VacantEntry {
1181 node: null_mut(),
1182 tree: self,
1183 direction: DIR_RIGHT,
1184 key: Last(),
1185 })
1186 }
1187 }
1188
1189 #[inline]
1190 pub fn validate(&self)
1191 where
1192 P::Target: Ord,
1193 {
1194 self.validate_with(P::Target::cmp)
1195 }
1196
1197 pub fn validate_with<F>(&self, cmp_f: F)
1198 where
1199 F: Fn(&P::Target, &P::Target) -> Ordering,
1200 {
1201 let validate_node = |data: *mut P::Target| unsafe {
1202 let node = (*data).get_node();
1203 let left = node.left();
1204 if !left.is_null() {
1205 assert!(cmp_f(&*left, &*data) != Ordering::Greater);
1206 assert_eq!((*left).get_node().get_parent(), data);
1207 }
1208 let right = node.right();
1209 if !right.is_null() {
1210 assert!(cmp_f(&*right, &*data) != Ordering::Less);
1211 assert_eq!((*right).get_node().get_parent(), data);
1212 }
1213 };
1214 let c = {
1215 #[cfg(feature = "std")]
1216 {
1217 ((self.len() + 10) as f32).log2() as usize
1218 }
1219 #[cfg(not(feature = "std"))]
1220 {
1221 100
1222 }
1223 };
1224 let mut stack: Vec<*mut P::Target> = Vec::with_capacity(c);
1225 if self.root.is_null() {
1226 assert_eq!(self.count, 0);
1227 return;
1228 }
1229 let mut data = self.root;
1230 let mut visited = 0;
1231 loop {
1232 if !data.is_null() {
1233 let left = unsafe { (*data).get_node() }.get_child(DIR_LEFT);
1234 if !left.is_null() {
1235 crate::trace_log!("validate: push {data:p}");
1236 stack.push(data);
1237 data = left;
1238 continue;
1239 }
1240 } else if !stack.is_empty() {
1241 data = stack.pop().unwrap();
1242 } else {
1243 break;
1244 }
1245 crate::trace_log!("validate: {data:p}");
1246 validate_node(data);
1247 visited += 1;
1248 data = unsafe { (*data).get_node() }.get_child(DIR_RIGHT);
1249 }
1250 assert_eq!(visited, self.count);
1251 }
1252}
1253
1254impl<P, Tag> Drop for AvlTree<P, Tag>
1255where
1256 P: Pointer,
1257 P::Target: AvlItem<Tag>,
1258{
1259 fn drop(&mut self) {
1260 let mut iter = AvlIntoIter::<P, Tag>::new(self.root, DIR_LEFT);
1262 for _node in iter.by_ref() {}
1263 core::mem::forget(iter);
1264 }
1265}
1266
1267impl<'a, P, Tag> core::iter::IntoIterator for &'a AvlTree<P, Tag>
1268where
1269 P: Pointer,
1270 P::Target: AvlItem<Tag>,
1271{
1272 type Item = AvlNodeRef<'a, P>;
1273 type IntoIter = AvlIter<'a, P, Tag>;
1274
1275 #[inline]
1276 fn into_iter(self) -> Self::IntoIter {
1277 self.iter()
1278 }
1279}
1280
1281impl<P, Tag> core::iter::IntoIterator for AvlTree<P, Tag>
1282where
1283 P: Pointer,
1284 P::Target: AvlItem<Tag>,
1285{
1286 type Item = P;
1287 type IntoIter = AvlIntoIter<P, Tag>;
1288
1289 #[inline]
1290 fn into_iter(self) -> Self::IntoIter {
1291 let node = self.root;
1292 core::mem::forget(self);
1293 AvlIntoIter::new(node, DIR_LEFT)
1294 }
1295}
1296
1297pub struct AvlNodeRef<'a, P: Pointer> {
1299 node: NonNull<P::Target>,
1300 _phan: PhantomData<&'a P>,
1301}
1302
1303impl<'a, P: Pointer> fmt::Debug for AvlNodeRef<'a, P>
1304where
1305 P::Target: fmt::Debug,
1306{
1307 #[inline]
1308 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1309 self.as_ref().fmt(f)
1310 }
1311}
1312
1313impl<'a, P: Pointer> AsRef<P::Target> for AvlNodeRef<'a, P> {
1314 #[inline(always)]
1315 fn as_ref(&self) -> &P::Target {
1316 unsafe { self.node.as_ref() }
1317 }
1318}
1319
1320impl<'a, P: Pointer> Deref for AvlNodeRef<'a, P> {
1321 type Target = P::Target;
1322
1323 #[inline(always)]
1324 fn deref(&self) -> &P::Target {
1325 unsafe { self.node.as_ref() }
1326 }
1327}
1328
1329impl<'a, P: Pointer> AvlNodeRef<'a, P> {
1330 #[inline]
1331 fn new(p: *mut P::Target) -> Self {
1332 Self { node: unsafe { NonNull::new_unchecked(p) }, _phan: Default::default() }
1333 }
1334}
1335
1336impl<'a, P: CloneablePointer> AvlNodeRef<'a, P> {
1337 #[inline]
1339 pub fn clone_ref(&self) -> P {
1340 unsafe { CloneablePointer::from_raw_and_clone(self.node.as_ptr()) }
1341 }
1342}