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    //
394    // # Arguments:
395    // - `parent`: this pointer to this node (we don't know the offset here)
396    #[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        // this is AvlTree::parent_direction in previous version
414        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        // this is AvlTree::parent_direction2 in previous version
436        let parent = unsafe { (*node).get_node() }.get_parent();
437        Self::child_direction(parent, node)
438    }
439
440    // Swap two node but not there value
441    #[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
477/// An intrusive AVL tree (balanced binary search tree).
478///
479/// Elements in the tree must implement the [`AvlItem`] trait.
480/// The tree supports various pointer types (`Box`, `Arc`, `Rc`, etc.) through the [`Pointer`] trait.
481pub 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    /// Creates a new, empty `AvlTree`.
545    #[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    /// Adds a new node to the tree, requires P::Target has `Ord`.
561    ///
562    /// (If you want more freedom of Ordering, see also [Self::entry_with])
563    ///
564    /// - Returns `Ok(())` if the node was added, takes the ownership of P.
565    /// - Err(P) if an equivalent node already exists
566    #[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                    // match is actually better optimized than if-else or table mapping
576                    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    /// remove a node from the tree (need P::Target to impl Borrow)
599    #[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    /// remove a node from the tree (useful if P is multiple ownership)
614    #[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    /// Searches for an element in the tree with `key`, requires P::Target can borrow to `K` type,
626    /// and have a total ordering by `K`.
627    #[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    /// Searches for an element in the tree with `key` and custom compare function.
637    #[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                // match is actually better optimized than if-else or table mapping
646                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                // match is actually better optimized than if-else or table mapping
690                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, // parent
713        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            /*
722             * Now, back up the tree modifying the balance of all nodes above the
723             * insertion point. If we get to a highly unbalanced ancestor, we
724             * need to do a rotation.  If we back out of the tree we are done.
725             * If we brought any subtree into perfect balance (0), we are also done.
726             */
727            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    /// Insert `new_ptr` in `tree` in the given `direction` against the node `here`.
756    ///
757    /// For range-tree scenario
758    ///
759    /// Insertions can only be done at empty leaf points in the tree, therefore
760    /// if the given child of the node is already present we move to either
761    /// the AVL_PREV or AVL_NEXT and reverse the insertion direction. Since
762    /// every other node in the tree is a leaf, this always works.
763    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        /* when balance = -2, left will be 0 */
786        //let dir = if balance < 0 { DIR_LEFT } else { DIR_RIGHT };
787        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        // node is overly left heavy, the left child is balanced or also left heavy.
802        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            // move node to be child's right child
808            node.balance = -child_balance;
809
810            node.parent = child;
811            child_node.set_child(dir_inverse, data);
812            // update the pointer into this subtree
813
814            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        // When node is left heavy, but child is right heavy we use
825        // a different rotation.
826
827        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        /*
836         * move child to left child of gchild and
837         * move node to right child of gchild and
838         * fixup parent of all this to point to gchild
839         */
840
841        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    /// Requires `del` to be a valid pointer to a node in this tree.
871    ///
872    /// # Safety
873    ///
874    /// It does not drop the node data, only unlinks it.
875    /// Caller is responsible for re-taking ownership (e.g. via from_raw) and dropping if needed.
876    ///
877    /// For Arc/Rc, use [Self::remove_ref()] instead.
878    ///
879    pub(crate) unsafe fn _remove(&mut self, del: *mut P::Target) {
880        /*
881         * Deletion is easiest with a node that has at most 1 child.
882         * We swap a node with 2 children with a sequentially valued
883         * neighbor node. That node will have at most 1 child. Note this
884         * has no effect on the ordering of the remaining nodes.
885         *
886         * As an optimization, we choose the greater neighbor if the tree
887         * is right heavy, otherwise the left neighbor. This reduces the
888         * number of rotations needed.
889         */
890        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        // Use reference directly to get node, avoiding unsafe dereference of raw pointer
902        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            // Fix Miri UB: Avoid calling parent_direction(child) if child's parent is del,
916            // because that would create a aliasing &mut ref to del while we hold del_node.
917            let dir_child_temp = if child == child_temp {
918                dir
919            } else {
920                AvlNode::<P::Target, Tag>::parent_direction(child)
921            };
922
923            // Fix Miri UB: Do not call parent_direction(del) as it creates a new &mut AvlNode
924            // alias while we hold del_node. Use del_node to find parent direction.
925            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            // move 'node' to delete's spot in the tree
932            if child_node.get_child(dir) == child {
933                // if node(d) left child is node(c)
934                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            // Put tmp where node used to be (just temporary).
959            // It always has a parent and at most 1 child.
960            let parent = del_node.get_parent();
961            unsafe { (*parent).get_node() }.set_child(dir_child_temp, del);
962            // if right exist, go to right
963            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        // Here we know "delete" is at least partially a leaf node. It can
975        // be easily removed from the tree.
976        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        // Connect parent directly to node (leaving out delete).
990
991        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            //Since the subtree is now shorter, begin adjusting parent balances
999            //and performing any needed rotations.
1000            let mut node_data: *mut P::Target = parent;
1001            loop {
1002                // Move up the tree and adjust the balance.
1003                // Capture the parent and which_child values for the next
1004                // iteration before any rotations occur.
1005                let node = unsafe { (*node_data).get_node() };
1006                let balance_delta = -which_child.to_balance();
1007                let old_balance = node.balance;
1008
1009                //If a node was in perfect balance but isn't anymore then
1010                //we can stop, since the height didn't change above this point
1011                //due to a deletion.
1012                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 the new balance is zero, we don't need to rotate
1022                //else
1023                //need a rotation to fix the balance.
1024                //If the rotation doesn't change the height
1025                //of the sub-tree we have finished adjusting.
1026                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    /// return a iterator to get the reference
1064    ///
1065    /// NOTE: The iterator yield [AvlNodeRef], so that you can clone the reference if it's `Arc`
1066    #[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    /// return a reversed iterator to get the reference.
1077    ///
1078    /// NOTE: The iterator yield [AvlNodeRef], so that you can clone the reference if it's `Arc`
1079    #[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    /// Into reversed order iterator that consume the items
1090    #[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                // move to upper parent
1121                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            // reach root
1128            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    /// 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        // It's intrusive, use standard into_iter to cleanup the AvlNode by resetting pointers
1261        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
1297/// A Reference to `P`
1298pub 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    /// If P is `Rc`/`Arc`, you can clone the reference out
1338    #[inline]
1339    pub fn clone_ref(&self) -> P {
1340        unsafe { CloneablePointer::from_raw_and_clone(self.node.as_ptr()) }
1341    }
1342}