Skip to main content

embed_avl/
lib.rs

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)]
5//! An intrusive AVL tree implementation.
6//!
7//! The algorithm origin from open-zfs
8//!
9//! benchmarks: <https://github.com/NaturalIO/embed-collections-rs/wiki>
10//!
11//! The ordering of avl tree is defined by [AvlItem] trait. There're two usage:
12//! - borrow field as key from the node struct
13//! - impl Ord for struct itself
14//!
15//! We provide Entry API to achieve `CursorMut` like ability, you can use the following combination:
16//! - [AvlTree::entry], [AvlTree::first_entry], [AvlTree::last_entry]
17//! - [OccupiedEntry::peek_prev], [OccupiedEntry::peek_next]
18//! - [OccupiedEntry::move_prev], [OccupiedEntry::move_next]
19//! - [OccupiedEntry::insert_prev_unchecked], [OccupiedEntry::insert_next_unchecked]  ( does not change current `OccupiedEntry`)
20//! - [OccupiedEntry::insert_move_prev_unchecked], OccupiedEntry::insert_move_next_unchecked] (return the newlly inserted OccupiedEntry, reduce additional seek cost)
21//! - [OccupiedEntry::remove_prev] , [OccupiedEntry::remove_next] (does not change current `OccupiedEntry`)
22//!
23//!
24//! Refer to the example of [AvlItem] document.
25//!
26//! # Examples
27//!
28//! ## Using `Box` to search and remove by key
29//!
30//! ```rust
31//! use embed_avl::{AvlTree, AvlItem, AvlNode, Entry, impl_ord_with_borrow};
32//! use core::cell::UnsafeCell;
33//! use core::borrow::Borrow;
34//! extern crate format_attr;
35//!
36//! #[derive(format_attr::DebugAttr)]
37//! #[fmt("MyNode {value}")]
38//! struct MyNode {
39//!     value: i32,
40//!     avl_node: UnsafeCell<AvlNode<MyNode, ()>>,
41//! }
42//!
43//! impl Borrow<i32> for MyNode {
44//!     fn borrow(&self) -> &i32 {
45//!         &self.value
46//!     }
47//! }
48//!
49//! unsafe impl AvlItem<()> for MyNode {
50//!     fn get_node(&self) -> &mut AvlNode<MyNode, ()> {
51//!         unsafe { &mut *self.avl_node.get() }
52//!     }
53//! }
54//!
55//! impl_ord_with_borrow!(MyNode, i32);
56//!
57//! let mut tree = AvlTree::<Box<MyNode>, ()>::new();
58//! tree.add(Box::new(MyNode { value: 10, avl_node: UnsafeCell::new(Default::default()) })).expect("add ok");
59//!
60//! // Search and remove
61//! if let Some(node) = tree.remove_by_key::<i32>(&10i32) {
62//!     assert_eq!(node.value, 10);
63//! }
64//! assert!(tree.is_empty());
65//!
66//! ```
67//!
68//! ## Using `Arc` to search and remove by node
69//!
70//! ```rust
71//! use embed_avl::{AvlTree, AvlItem, AvlNode, Entry, impl_ord_with_borrow};
72//! use core::cell::UnsafeCell;
73//! use core::borrow::Borrow;
74//! extern crate format_attr;
75//! extern crate alloc;
76//! use alloc::sync::Arc;
77//!
78//! #[derive(format_attr::DebugAttr)]
79//! #[fmt("MyNode {value}")]
80//! struct MyNode {
81//!     value: i32,
82//!     avl_node: UnsafeCell<AvlNode<MyNode, ()>>,
83//! }
84//!
85//! impl Borrow<i32> for MyNode {
86//!     fn borrow(&self) -> &i32 {
87//!         &self.value
88//!     }
89//! }
90//!
91//! unsafe impl AvlItem<()> for MyNode {
92//!     fn get_node(&self) -> &mut AvlNode<MyNode, ()> {
93//!         unsafe { &mut *self.avl_node.get() }
94//!     }
95//! }
96//!
97//! impl_ord_with_borrow!(MyNode, i32);
98//!
99//! // Using `Arc` for multiple ownership
100//! // remove_ref only available to `Arc` and `Rc`
101//!
102//! let mut tree = AvlTree::<Arc<MyNode>, ()>::new();
103//! let node = Arc::new(MyNode { value: 42, avl_node: UnsafeCell::new(Default::default()) });
104//!
105//! // Alternative way of insert
106//! if let Entry::Vacant(ent) = tree.entry(node.value) {
107//!     ent.insert_node(node.clone());
108//! } else {
109//!     unreachable!();
110//! }
111//! assert_eq!(tree.len(), 1);
112//!
113//! // Remove by reference (detach from avl tree)
114//! tree.remove(&node);
115//! assert_eq!(tree.len(), 0);
116//! ```
117//!
118//! ## Efficient bulk insertion
119//!
120//! ```rust
121//! use embed_avl::{AvlTree, AvlItem, AvlNode, Entry, impl_ord_with_borrow};
122//! use core::cell::UnsafeCell;
123//! use core::borrow::Borrow;
124//! extern crate format_attr;
125//!
126//! #[derive(format_attr::DebugAttr)]
127//! #[fmt("MyNode {value}")]
128//! struct MyNode {
129//!     value: i32,
130//!     avl_node: UnsafeCell<AvlNode<MyNode, ()>>,
131//! }
132//!
133//! impl Borrow<i32> for MyNode {
134//!     fn borrow(&self) -> &i32 {
135//!         &self.value
136//!     }
137//! }
138//!
139//! unsafe impl AvlItem<()> for MyNode {
140//!     fn get_node(&self) -> &mut AvlNode<MyNode, ()> {
141//!         unsafe { &mut *self.avl_node.get() }
142//!     }
143//! }
144//!
145//! impl_ord_with_borrow!(MyNode, i32);
146//!
147//! let mut tree = AvlTree::<Box<MyNode>, ()>::new();
148//! let mut ent = tree.last_entry();
149//! for i in 0..100 {
150//!     ent = unsafe{ent.append_unchecked(
151//!         Box::new(MyNode { value: i, avl_node: UnsafeCell::new(Default::default()) })
152//!     )};
153//! }
154//!
155//! // Search
156//! if let Some(node) = tree.get::<i32>(&10) {
157//!     assert_eq!(node.value, 10);
158//! }
159//! assert_eq!(tree.len(), 100);
160//!
161//! ```
162
163extern 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
185/// A trait to return internal mutable AvlNode for specified list.
186///
187/// The tag is used to distinguish different AvlNodes within the same item,
188/// allowing an item to belong to multiple lists simultaneously.
189/// For only one ownership, you can use `()`.
190///
191/// # Safety
192///
193/// Implementors must ensure `get_node` returns a valid reference to the `AvlNode`
194/// embedded within `Self`. Users must use `UnsafeCell` to hold `AvlNode` to support
195/// interior mutability required by list operations.
196///
197/// # Example (struct field as key)
198///
199/// ```
200/// use embed_avl::{AvlItem, AvlNode, impl_ord_with_borrow};
201/// extern crate format_attr;
202/// use core::borrow::Borrow;
203/// use core::cell::UnsafeCell;
204///
205/// #[derive(format_attr::DebugAttr)]
206/// #[fmt("IntAvlNode {value}")]
207/// pub struct IntAvlNode {
208///     pub value: i64,
209///     pub node: UnsafeCell<AvlNode<Self, ()>>,
210/// }
211///
212/// unsafe impl AvlItem<()> for IntAvlNode {
213///     fn get_node(&self) -> &mut AvlNode<Self, ()> {
214///         unsafe { &mut *self.node.get() }
215///     }
216/// }
217///
218/// impl Borrow<i64> for IntAvlNode {
219///     fn borrow(&self) -> &i64 {
220///         &self.value
221///     }
222/// }
223///
224/// impl_ord_with_borrow!(IntAvlNode, i64);
225/// ```
226///
227/// # Example (impl Ord for struct)
228///
229/// ```
230/// use embed_avl::{AvlItem, AvlNode};
231/// use core::cell::{Cell, UnsafeCell};
232/// use core::cmp::Ordering;
233///
234/// pub struct RangeSeg {
235///     node: UnsafeCell<AvlNode<Self, ()>>,
236///     pub start: Cell<u64>,
237///     pub end: Cell<u64>,
238/// }
239///
240/// impl PartialOrd for RangeSeg {
241///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
242///         Some(Ord::cmp(self, other))
243///     }
244/// }
245/// impl PartialEq for RangeSeg {
246///     fn eq(&self, other: &Self) -> bool {
247///         Ord::cmp(self, other) == Ordering::Equal
248///     }
249/// }
250/// impl Eq for RangeSeg {}
251///
252/// impl Ord for RangeSeg {
253///     fn cmp(&self, other: &Self) -> Ordering {
254///         if self.end.get() <= other.start.get() {
255///             Ordering::Less
256///         } else if self.start.get() >= other.end.get() {
257///             Ordering::Greater
258///         } else {
259///             // intersection
260///             Ordering::Equal
261///         }
262///     }
263/// }
264/// unsafe impl Send for RangeSeg {}
265/// unsafe impl AvlItem<()> for RangeSeg {
266///     fn get_node(&self) -> &mut AvlNode<Self, ()> {
267///         unsafe { &mut *self.node.get() }
268///     }
269/// }
270/// ```
271pub unsafe trait AvlItem<Tag>: Sized {
272    fn get_node(&self) -> &mut AvlNode<Self, Tag>;
273}
274
275/// Implement Ord with `Borrow<K>`
276///
277/// # Arguments
278/// - cls: struct name
279/// - key_type: `cls: Borrow<$key_type>`
280#[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/// logging macro for development
304#[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    // set child and both child's parent
393    #[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        // this is AvlTree::parent_direction in previous version
411        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        // this is AvlTree::parent_direction2 in previous version
433        let parent = unsafe { (*node).get_node() }.get_parent();
434        Self::child_direction(parent, node)
435    }
436
437    // Swap two node but not there value
438    #[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
474/// An intrusive AVL tree (balanced binary search tree).
475///
476/// Elements in the tree must implement the [`AvlItem`] trait.
477/// The tree supports various pointer types (`Box`, `Arc`, `Rc`, etc.) through the [`Pointer`] trait.
478pub 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    /// Creates a new, empty `AvlTree`.
542    #[inline]
543    pub fn new() -> Self {
544        AvlTree { count: 0, root: null_mut(), _phan: Default::default() }
545    }
546
547    /// Returns an iterator that removes all elements from the tree in post-order.
548    ///
549    /// This is an optimized, non-recursive, and stack-less traversal that preserves
550    /// tree invariants during destruction.
551    #[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    /// Adds a new node to the tree, requires P::Target has `Ord`.
567    ///
568    /// (If you want more freedom of Ordering, see also [Self::entry_with])
569    ///
570    /// - Returns `Ok(())` if the node was added, takes the ownership of P.
571    /// - Err(P) if an equivalent node already exists
572    #[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                    // match is actually better optimized than if-else or table mapping
582                    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    /// remove a node from the tree (need P::Target to impl Borrow)
605    #[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    /// remove a node from the tree (useful if P is multiple ownership)
620    #[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    /// Searches for an element in the tree with `key`, requires P::Target can borrow to `K` type,
632    /// and have a total ordering by `K`.
633    #[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    /// Searches for an element in the tree with `key` and custom compare function.
643    #[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                // match is actually better optimized than if-else or table mapping
652                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                // match is actually better optimized than if-else or table mapping
696                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, // parent
719        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            /*
728             * Now, back up the tree modifying the balance of all nodes above the
729             * insertion point. If we get to a highly unbalanced ancestor, we
730             * need to do a rotation.  If we back out of the tree we are done.
731             * If we brought any subtree into perfect balance (0), we are also done.
732             */
733            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    /// Insert `new_ptr` in `tree` in the given `direction` against the node `here`.
762    ///
763    /// For range-tree scenario
764    ///
765    /// Insertions can only be done at empty leaf points in the tree, therefore
766    /// if the given child of the node is already present we move to either
767    /// the AVL_PREV or AVL_NEXT and reverse the insertion direction. Since
768    /// every other node in the tree is a leaf, this always works.
769    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        /* when balance = -2, left will be 0 */
792        //let dir = if balance < 0 { DIR_LEFT } else { DIR_RIGHT };
793        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        // node is overly left heavy, the left child is balanced or also left heavy.
808        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            // move node to be child's right child
814            node.balance = -child_balance;
815
816            node.parent = child;
817            child_node.set_child(dir_inverse, data);
818            // update the pointer into this subtree
819
820            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        // When node is left heavy, but child is right heavy we use
831        // a different rotation.
832
833        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        /*
842         * move child to left child of gchild and
843         * move node to right child of gchild and
844         * fixup parent of all this to point to gchild
845         */
846
847        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    /// Requires `del` to be a valid pointer to a node in this tree.
877    ///
878    /// # Safety
879    ///
880    /// It does not drop the node data, only unlinks it.
881    /// Caller is responsible for re-taking ownership (e.g. via from_raw) and dropping if needed.
882    ///
883    /// For Arc/Rc, use [Self::remove_ref()] instead.
884    ///
885    pub(crate) unsafe fn _remove(&mut self, del: *mut P::Target) {
886        /*
887         * Deletion is easiest with a node that has at most 1 child.
888         * We swap a node with 2 children with a sequentially valued
889         * neighbor node. That node will have at most 1 child. Note this
890         * has no effect on the ordering of the remaining nodes.
891         *
892         * As an optimization, we choose the greater neighbor if the tree
893         * is right heavy, otherwise the left neighbor. This reduces the
894         * number of rotations needed.
895         */
896        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        // Use reference directly to get node, avoiding unsafe dereference of raw pointer
908        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            // Fix Miri UB: Avoid calling parent_direction(child) if child's parent is del,
922            // because that would create a aliasing &mut ref to del while we hold del_node.
923            let dir_child_temp = if child == child_temp {
924                dir
925            } else {
926                AvlNode::<P::Target, Tag>::parent_direction(child)
927            };
928
929            // Fix Miri UB: Do not call parent_direction(del) as it creates a new &mut AvlNode
930            // alias while we hold del_node. Use del_node to find parent direction.
931            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            // move 'node' to delete's spot in the tree
938            if child_node.get_child(dir) == child {
939                // if node(d) left child is node(c)
940                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            // Put tmp where node used to be (just temporary).
965            // It always has a parent and at most 1 child.
966            let parent = del_node.get_parent();
967            unsafe { (*parent).get_node() }.set_child(dir_child_temp, del);
968            // if right exist, go to right
969            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        // Here we know "delete" is at least partially a leaf node. It can
981        // be easily removed from the tree.
982        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        // Connect parent directly to node (leaving out delete).
996
997        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            //Since the subtree is now shorter, begin adjusting parent balances
1005            //and performing any needed rotations.
1006            let mut node_data: *mut P::Target = parent;
1007            loop {
1008                // Move up the tree and adjust the balance.
1009                // Capture the parent and which_child values for the next
1010                // iteration before any rotations occur.
1011                let node = unsafe { (*node_data).get_node() };
1012                let balance_delta = -which_child.to_balance();
1013                let old_balance = node.balance;
1014
1015                //If a node was in perfect balance but isn't anymore then
1016                //we can stop, since the height didn't change above this point
1017                //due to a deletion.
1018                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 the new balance is zero, we don't need to rotate
1028                //else
1029                //need a rotation to fix the balance.
1030                //If the rotation doesn't change the height
1031                //of the sub-tree we have finished adjusting.
1032                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    /// return a iterator to get the reference
1070    ///
1071    /// NOTE: The iterator yield [NodeRef], so that you can clone the reference if it's `Arc`
1072    #[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    /// return a reversed iterator to get the reference.
1083    ///
1084    /// NOTE: The iterator yield [NodeRef], so that you can clone the reference if it's `Arc`
1085    #[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    /// Get the last entry
1154    ///
1155    /// You can use [Entry::prepend] or [Entry::prepend_unchecked] on it to batch insert
1156    #[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    /// Get the last entry
1172    ///
1173    /// You can use [Entry::append] or [Entry::append_unchecked] on it to batch insert
1174    #[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
1266/// A Reference to `P`
1267pub 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    /// If P is `Rc`/`Arc`, you can clone the reference out
1297    #[inline]
1298    pub fn clone_ref(&self) -> P {
1299        unsafe { CloneablePointer::from_raw_and_clone(self.node.as_ptr()) }
1300    }
1301}