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)]
394 fn set_child2<P: Pointer<Target = T>>(
395 &mut self, dir: Dir, child: *mut P::Target, parent: *mut P::Target,
396 ) {
397 if !child.is_null() {
398 unsafe { (*child).get_node().parent = parent };
399 }
400 self.set_child(dir, child);
401 }
402
403 #[inline(always)]
404 fn get_parent(&self) -> *mut T {
405 self.parent
406 }
407
408 #[inline(always)]
409 fn _child_direction(&self, child_p: *mut T) -> Dir {
410 let is_right = self.children[1] == child_p;
412 #[cfg(debug_assertions)]
413 {
414 if !is_right {
415 debug_assert!(self.children[0] == child_p);
416 }
417 }
418 is_right.into()
419 }
420
421 #[inline(always)]
422 fn child_direction(parent: *mut T, child_p: *mut T) -> Dir {
423 if !parent.is_null() {
424 unsafe { (*parent).get_node() }._child_direction(child_p)
425 } else {
426 DIR_LEFT
427 }
428 }
429
430 #[inline(always)]
431 fn parent_direction(node: *mut T) -> Dir {
432 let parent = unsafe { (*node).get_node() }.get_parent();
434 Self::child_direction(parent, node)
435 }
436
437 #[inline(always)]
439 pub fn swap(&mut self, other: &mut AvlNode<T, Tag>) {
440 mem::swap(self, other);
441 }
442}
443
444impl<T: AvlItem<Tag>, Tag> Default for AvlNode<T, Tag> {
445 fn default() -> Self {
446 Self {
447 children: [null_mut(), null_mut()],
448 parent: null_mut(),
449 balance: 0,
450 _phan: Default::default(),
451 }
452 }
453}
454
455#[allow(unused_must_use)]
456impl<T: AvlItem<Tag>, Tag> fmt::Debug for AvlNode<T, Tag> {
457 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 write!(f, "(")?;
459 if !self.left().is_null() {
460 write!(f, "left: {:p}", self.left())?;
461 } else {
462 write!(f, "left: none ")?;
463 }
464
465 if !self.right().is_null() {
466 write!(f, "right: {:p}", self.right())?;
467 } else {
468 write!(f, "right: none ")?;
469 }
470 write!(f, ")")
471 }
472}
473
474pub struct AvlTree<P, Tag>
479where
480 P: Pointer,
481 P::Target: AvlItem<Tag>,
482{
483 root: *mut P::Target,
484 count: usize,
485 _phan: PhantomData<fn(P, &Tag)>,
486}
487
488impl<P, Tag> Default for AvlTree<P, Tag>
489where
490 P: Pointer + Send,
491 P::Target: AvlItem<Tag>,
492{
493 #[inline(always)]
494 fn default() -> Self {
495 Self::new()
496 }
497}
498
499unsafe impl<P, Tag> Send for AvlTree<P, Tag>
500where
501 P: Pointer + Send,
502 P::Target: AvlItem<Tag>,
503{
504}
505
506unsafe impl<P, Tag> Sync for AvlTree<P, Tag>
507where
508 P: Pointer + Send,
509 P::Target: AvlItem<Tag>,
510{
511}
512
513impl<P, Tag> fmt::Debug for AvlTree<P, Tag>
514where
515 P: Pointer,
516 P::Target: AvlItem<Tag> + fmt::Debug,
517{
518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
519 let _ = write!(f, "AvlTree{{");
520 if self.count > 0 {
521 let mut iter = self.iter();
522 loop {
523 let node = iter.next().unwrap();
524 let _ = write!(f, "{:?}", node.as_ref().as_ref());
525 if iter.len() > 0 {
526 let _ = write!(f, ", ");
527 } else {
528 break;
529 }
530 }
531 }
532 write!(f, "}}")
533 }
534}
535
536impl<P, Tag> AvlTree<P, Tag>
537where
538 P: Pointer,
539 P::Target: AvlItem<Tag>,
540{
541 #[inline]
543 pub fn new() -> Self {
544 AvlTree { count: 0, root: null_mut(), _phan: Default::default() }
545 }
546
547 #[inline]
552 pub fn drain(&mut self) -> AvlDrain<'_, P, Tag> {
553 AvlDrain::new(self)
554 }
555
556 #[inline]
557 pub fn is_empty(&self) -> bool {
558 self.count == 0
559 }
560
561 #[inline]
562 pub fn len(&self) -> usize {
563 self.count
564 }
565
566 #[inline]
573 pub fn add(&mut self, node: P) -> Result<(), P>
574 where
575 P::Target: Ord,
576 {
577 if !self.root.is_null() {
578 let mut parent = self.root;
579 unsafe {
580 loop {
581 let dir = match node.as_ref().cmp((&*parent).as_ref()) {
583 Ordering::Greater => DIR_RIGHT,
584 Ordering::Less => DIR_LEFT,
585 Ordering::Equal => return Err(node),
586 };
587 let child = (*parent).get_node().get_child(dir);
588 if !child.is_null() {
589 parent = child;
590 } else {
591 self._insert(node.into_raw() as *mut P::Target, parent, dir);
592 return Ok(());
593 }
594 }
595 }
596 } else {
597 debug_assert_eq!(self.count, 0);
598 self.root = node.into_raw() as *mut P::Target;
599 self.count = 1;
600 Ok(())
601 }
602 }
603
604 #[inline]
606 pub fn remove_by_key<K>(&mut self, key: &K) -> Option<P>
607 where
608 P::Target: Borrow<K>,
609 K: Ord,
610 {
611 let _cmp = |_key: &&K, node: &P::Target| -> Ordering { _key.cmp(&node.borrow()) };
612 if let Entry::Occupied(ent) = self.entry_with::<&K, _>(key, _cmp) {
613 Some(ent.remove())
614 } else {
615 None
616 }
617 }
618
619 #[inline]
621 pub fn remove(&mut self, node: &P)
622 where
623 P::Target: Ord,
624 {
625 let _cmp = |_cur: &&P::Target, node: &P::Target| -> Ordering { _cur.cmp(&node.borrow()) };
626 if let Entry::Occupied(ent) = self.entry_with::<&P::Target, _>(node.as_ref(), _cmp) {
627 ent.remove();
628 }
629 }
630
631 #[inline]
634 pub fn entry<'a, K>(&'a mut self, key: K) -> Entry<'a, P, Tag, K>
635 where
636 P::Target: Borrow<K>,
637 K: Ord,
638 {
639 self.entry_with(key, |_key: &K, node: &P::Target| _key.cmp(node.borrow()))
640 }
641
642 #[inline]
644 pub fn entry_with<'a, K, F>(&'a mut self, key: K, cmp_f: F) -> Entry<'a, P, Tag, K>
645 where
646 F: Fn(&K, &P::Target) -> Ordering,
647 {
648 if !self.root.is_null() {
649 let mut parent = self.root;
650 loop {
651 let dir = match cmp_f(&key, unsafe { &*parent }.as_ref()) {
653 Ordering::Greater => DIR_RIGHT,
654 Ordering::Less => DIR_LEFT,
655 Ordering::Equal => {
656 return Entry::Occupied(OccupiedEntry {
657 node: unsafe { NonNull::new_unchecked(parent) },
658 tree: self,
659 });
660 }
661 };
662 let child = unsafe { (*parent).get_node() }.get_child(dir);
663 if !child.is_null() {
664 parent = child;
665 } else {
666 return Entry::Vacant(VacantEntry {
667 node: parent,
668 direction: dir,
669 tree: self,
670 key,
671 });
672 }
673 }
674 } else {
675 Entry::Vacant(VacantEntry { node: null_mut(), direction: DIR_RIGHT, tree: self, key })
676 }
677 }
678
679 #[inline]
680 pub fn get<'a, K>(&'a self, key: &K) -> Option<NodeRef<'a, P>>
681 where
682 P::Target: Borrow<K>,
683 K: Ord,
684 {
685 self.get_with(|node| key.cmp(node.borrow()))
686 }
687
688 pub fn get_with<'a, F>(&'a self, cmp_f: F) -> Option<NodeRef<'a, P>>
689 where
690 F: Fn(&P::Target) -> Ordering,
691 {
692 if !self.root.is_null() {
693 let mut node = self.root;
694 loop {
695 let dir = match cmp_f(unsafe { &*node }.as_ref()) {
697 Ordering::Greater => DIR_RIGHT,
698 Ordering::Less => DIR_LEFT,
699 Ordering::Equal => return Some(NodeRef::new(node)),
700 };
701 let child = unsafe { (*node).get_node() }.get_child(dir);
702 if !child.is_null() {
703 node = child;
704 } else {
705 return None;
706 }
707 }
708 } else {
709 None
710 }
711 }
712
713 #[allow(clippy::not_unsafe_ptr_arg_deref)]
714 #[inline]
715 pub(crate) fn _insert(
716 &mut self,
717 new_ptr: *mut P::Target,
718 parent: *mut P::Target, mut which_child: Dir,
720 ) {
721 if !parent.is_null() {
722 let mut new_balance: i8;
723 unsafe { (*new_ptr).get_node() }.parent = parent;
724 let parent_node = unsafe { (*parent).get_node() };
725 parent_node.set_child(which_child, new_ptr);
726 self.count += 1;
727 let mut data: *mut P::Target = parent;
734 loop {
735 let node = unsafe { (*data).get_node() };
736 let old_balance = node.balance;
737 new_balance = old_balance + which_child.to_balance();
738 if new_balance == 0 {
739 node.balance = 0;
740 return;
741 }
742 if old_balance != 0 {
743 break;
744 }
745 node.balance = new_balance;
746 let parent_ptr = node.get_parent();
747 if parent_ptr.is_null() {
748 return;
749 }
750 which_child = unsafe { (*parent_ptr).get_node() }._child_direction(data);
751 data = parent_ptr;
752 }
753 self.rotate(data, new_balance);
754 } else {
755 debug_assert_eq!(self.count, 0);
756 self.root = new_ptr;
757 self.count += 1;
758 }
759 }
760
761 unsafe fn _insert_here(
770 &mut self, new_ptr: *mut P::Target, here: NonNull<P::Target>, direction: Dir,
771 ) {
772 crate::trace_log!("_insert_here {new_ptr:p} here {here:p} dir {direction:?}");
773 let mut dir_child = direction;
774 unsafe {
775 let child = here.as_ref().get_node().get_child(dir_child);
776 let parent;
777 if child.is_null() {
778 crate::trace_log!("direct at here {here:p}");
779 parent = here;
780 } else {
781 dir_child = dir_child.reverse();
782 parent = self.bottom_child(NonNull::new_unchecked(child), dir_child);
783 crate::trace_log!("find bottom {parent:p}");
784 }
785 self._insert(new_ptr, parent.as_ptr(), dir_child);
786 }
787 }
788
789 #[inline]
790 fn rotate(&mut self, data: *mut P::Target, balance: i8) -> bool {
791 let dir: Dir = (balance >= 0).into();
794 let node = unsafe { (*data).get_node() };
795
796 let parent = node.get_parent();
797 let dir_inverse = dir.reverse();
798 let left_heavy = balance >> 1;
799 let right_heavy = -left_heavy;
800
801 let child = node.get_child(dir);
802 let child_node = unsafe { (*child).get_node() };
803 let mut child_balance = child_node.balance;
804
805 let which_child = AvlNode::<P::Target, Tag>::child_direction(parent, data);
806
807 if child_balance != right_heavy {
809 child_balance += right_heavy;
810
811 let c_right = child_node.get_child(dir_inverse);
812 node.set_child2::<P>(dir, c_right, data);
813 node.balance = -child_balance;
815
816 node.parent = child;
817 child_node.set_child(dir_inverse, data);
818 child_node.balance = child_balance;
821 if !parent.is_null() {
822 child_node.parent = parent;
823 unsafe { (*parent).get_node() }.set_child(which_child, child);
824 } else {
825 child_node.parent = null_mut();
826 self.root = child;
827 }
828 return child_balance == 0;
829 }
830 let g_child = child_node.get_child(dir_inverse);
834 let g_child_node = unsafe { (*g_child).get_node() };
835 let g_left = g_child_node.get_child(dir);
836 let g_right = g_child_node.get_child(dir_inverse);
837
838 node.set_child2::<P>(dir, g_right, data);
839 child_node.set_child2::<P>(dir_inverse, g_left, child);
840
841 let g_child_balance = g_child_node.balance;
848 if g_child_balance == right_heavy {
849 child_node.balance = left_heavy;
850 } else {
851 child_node.balance = 0;
852 }
853 child_node.parent = g_child;
854 g_child_node.set_child(dir, child);
855
856 if g_child_balance == left_heavy {
857 node.balance = right_heavy;
858 } else {
859 node.balance = 0;
860 }
861 g_child_node.balance = 0;
862
863 node.parent = g_child;
864 g_child_node.set_child(dir_inverse, data);
865
866 if !parent.is_null() {
867 g_child_node.parent = parent;
868 unsafe { (*parent).get_node() }.set_child(which_child, g_child);
869 } else {
870 g_child_node.parent = null_mut();
871 self.root = g_child;
872 }
873 true
874 }
875
876 pub(crate) unsafe fn _remove(&mut self, del: *mut P::Target) {
886 if self.count == 0 {
897 return;
898 }
899 if self.count == 1 && self.root == del {
900 self.root = null_mut();
901 self.count = 0;
902 unsafe { (*del).get_node().detach() };
903 return;
904 }
905 let mut which_child: Dir;
906
907 let del_node = unsafe { (*del).get_node() };
909
910 let node_swap_flag = !del_node.left().is_null() && !del_node.right().is_null();
911
912 if node_swap_flag {
913 let dir: Dir = balance_to_child!(del_node.balance + 1);
914 let child_temp = del_node.get_child(dir);
915
916 let dir_inverse: Dir = dir.reverse();
917 let child = self
918 .bottom_child(unsafe { NonNull::new_unchecked(child_temp) }, dir_inverse)
919 .as_ptr();
920
921 let dir_child_temp = if child == child_temp {
924 dir
925 } else {
926 AvlNode::<P::Target, Tag>::parent_direction(child)
927 };
928
929 let parent = del_node.get_parent();
932 let dir_child_del = AvlNode::<P::Target, Tag>::child_direction(parent, del);
933
934 let child_node = unsafe { (*child).get_node() };
935 child_node.swap(del_node);
936
937 if child_node.get_child(dir) == child {
939 child_node.set_child(dir, del);
941 }
942
943 let c_dir = child_node.get_child(dir);
944 if c_dir == del {
945 del_node.parent = child;
946 } else if !c_dir.is_null() {
947 unsafe { (*c_dir).get_node() }.parent = child;
948 }
949
950 let c_inv = child_node.get_child(dir_inverse);
951 if c_inv == del {
952 del_node.parent = child;
953 } else if !c_inv.is_null() {
954 unsafe { (*c_inv).get_node() }.parent = child;
955 }
956
957 let parent = child_node.get_parent();
958 if !parent.is_null() {
959 unsafe { (*parent).get_node() }.set_child(dir_child_del, child);
960 } else {
961 self.root = child;
962 }
963
964 let parent = del_node.get_parent();
967 unsafe { (*parent).get_node() }.set_child(dir_child_temp, del);
968 which_child = Dir(!del_node.right().is_null());
970 let child = del_node.get_child(which_child);
971 if !child.is_null() {
972 unsafe { (*child).get_node() }.parent = del;
973 }
974 which_child = dir_child_temp;
975 } else {
976 let parent = del_node.get_parent();
977 which_child = AvlNode::<P::Target, Tag>::child_direction(parent, del);
978 }
979
980 let parent: *mut P::Target = del_node.get_parent();
983
984 let mut imm_data: *mut P::Target = del_node.left();
985 if !imm_data.is_null() {
986 let imm_node = unsafe { (*imm_data).get_node() };
987 imm_node.parent = parent;
988 } else {
989 imm_data = del_node.right();
990 if !imm_data.is_null() {
991 let imm_node = unsafe { (*imm_data).get_node() };
992 imm_node.parent = parent;
993 }
994 }
995 if !parent.is_null() {
998 assert!(self.count > 0);
999 self.count -= 1;
1000
1001 let parent_node = unsafe { (*parent).get_node() };
1002 parent_node.set_child(which_child, imm_data);
1003
1004 let mut node_data: *mut P::Target = parent;
1007 loop {
1008 let node = unsafe { (*node_data).get_node() };
1012 let balance_delta = -which_child.to_balance();
1013 let old_balance = node.balance;
1014
1015 if old_balance == 0 {
1019 node.balance = balance_delta;
1020 break;
1021 }
1022 let new_balance = old_balance + balance_delta;
1023
1024 let parent = node.get_parent();
1025 which_child = AvlNode::<P::Target, Tag>::child_direction(parent, node_data);
1026
1027 if new_balance == 0 {
1033 node.balance = 0;
1034 } else if !self.rotate(node_data, new_balance) {
1035 break;
1036 }
1037
1038 if !parent.is_null() {
1039 node_data = parent;
1040 continue;
1041 }
1042 break;
1043 }
1044 } else if !imm_data.is_null() {
1045 debug_assert!(self.count > 0);
1046 self.count -= 1;
1047 self.root = imm_data;
1048 }
1049 if self.root.is_null() && self.count > 0 {
1050 panic!("AvlTree {} nodes left after remove but tree.root == nil", self.count);
1051 }
1052 del_node.detach();
1053 }
1054
1055 #[inline(always)]
1056 fn bottom_child(&self, mut data: NonNull<P::Target>, dir: Dir) -> NonNull<P::Target> {
1057 loop {
1058 unsafe {
1059 let child = data.as_ref().get_node().get_child(dir);
1060 if !child.is_null() {
1061 data = NonNull::new_unchecked(child);
1062 } else {
1063 return data;
1064 }
1065 }
1066 }
1067 }
1068
1069 #[inline]
1073 pub fn iter(&self) -> AvlIter<'_, P, Tag> {
1074 let first_p = if !self.root.is_null() {
1075 Some(self.bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_LEFT))
1076 } else {
1077 None
1078 };
1079 AvlIter::new(self, first_p, DIR_RIGHT)
1080 }
1081
1082 #[inline]
1086 pub fn iter_rev(&self) -> AvlIter<'_, P, Tag> {
1087 let last_p = if !self.root.is_null() {
1088 Some(self.bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_RIGHT))
1089 } else {
1090 None
1091 };
1092 AvlIter::new(self, last_p, DIR_LEFT)
1093 }
1094
1095 #[inline]
1096 pub fn prev<'a>(&'a self, data: &'a P::Target) -> Option<NodeRef<'a, P>> {
1097 self._walk_dir(data.into(), DIR_LEFT).map(|p| NodeRef::new(p.as_ptr()))
1098 }
1099
1100 #[inline]
1101 pub fn next<'a>(&'a self, data: &'a P::Target) -> Option<NodeRef<'a, P>> {
1102 self._walk_dir(data.into(), DIR_RIGHT).map(|p| NodeRef::new(p.as_ptr()))
1103 }
1104
1105 fn _walk_dir(&self, mut data_ptr: NonNull<P::Target>, dir: Dir) -> Option<NonNull<P::Target>> {
1106 let dir_inverse = dir.reverse();
1107 let node = unsafe { data_ptr.as_ref().get_node() };
1108 let temp = node.get_child(dir);
1109 if !temp.is_null() {
1110 unsafe { Some(self.bottom_child(NonNull::new_unchecked(temp), dir_inverse)) }
1111 } else {
1112 let mut parent = node.parent;
1113 if parent.is_null() {
1114 return None;
1115 }
1116 loop {
1117 let pdir = AvlNode::<P::Target, Tag>::child_direction(parent, data_ptr.as_ptr());
1118 if pdir == dir_inverse {
1119 return Some(unsafe { NonNull::new_unchecked(parent) });
1120 }
1121 let data_ptr_raw = parent;
1122 parent = unsafe { (*parent).get_node() }.parent;
1123 if parent.is_null() {
1124 return None;
1125 }
1126 unsafe {
1127 data_ptr = NonNull::new_unchecked(data_ptr_raw);
1128 }
1129 }
1130 }
1131 }
1132
1133 #[inline]
1134 pub fn first<'a>(&'a self) -> Option<NodeRef<'a, P>> {
1135 if !self.root.is_null() {
1136 let p = self.bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_LEFT);
1137 Some(NodeRef::<'a, P>::new(p.as_ptr()))
1138 } else {
1139 None
1140 }
1141 }
1142
1143 #[inline]
1144 pub fn last<'a>(&'a self) -> Option<NodeRef<'a, P>> {
1145 if !self.root.is_null() {
1146 let p = self.bottom_child(unsafe { NonNull::new_unchecked(self.root) }, DIR_RIGHT);
1147 Some(NodeRef::<'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 if mem::needs_drop::<P>() {
1261 for _ in self.drain() {}
1262 }
1263 }
1264}
1265
1266pub struct NodeRef<'a, P: Pointer> {
1268 node: NonNull<P::Target>,
1269 _phan: PhantomData<&'a P>,
1270}
1271
1272impl<'a, P: Pointer> AsRef<P::Target> for NodeRef<'a, P> {
1273 #[inline(always)]
1274 fn as_ref(&self) -> &P::Target {
1275 unsafe { self.node.as_ref() }
1276 }
1277}
1278
1279impl<'a, P: Pointer> Deref for NodeRef<'a, P> {
1280 type Target = P::Target;
1281
1282 #[inline(always)]
1283 fn deref(&self) -> &P::Target {
1284 unsafe { self.node.as_ref() }
1285 }
1286}
1287
1288impl<'a, P: Pointer> NodeRef<'a, P> {
1289 #[inline]
1290 fn new(p: *mut P::Target) -> Self {
1291 Self { node: unsafe { NonNull::new_unchecked(p) }, _phan: Default::default() }
1292 }
1293}
1294
1295impl<'a, P: CloneablePointer> NodeRef<'a, P> {
1296 #[inline]
1298 pub fn clone_ref(&self) -> P {
1299 unsafe { CloneablePointer::from_raw_and_clone(self.node.as_ptr()) }
1300 }
1301}