Skip to main content

rbt_rs/
lib.rs

1//! This module implements a binary search tree in the form of a [Red-black tree](https://en.wikipedia.org/wiki/Red–black_tree), which is an approximately balanced binary search tree.
2//!
3//! All [`RedBlackTree`] tree binary search tree operations: [`insert`], [`remove`], [`contains`], [`min`], [`max`], [`predecessor`], [`successor`] have a worst case time complexity of `O(log n)`.
4//!
5//! [`insert`]: RedBlackTree::insert
6//! [`remove`]: RedBlackTree::remove
7//! [`contains`]: RedBlackTree::contains
8//! [`min`]: RedBlackTree::min
9//! [`max`]: RedBlackTree::max
10//! [`predecessor`]: RedBlackTree::predecessor
11//! [`successor`]: RedBlackTree::successor
12//!
13//! # Examples:
14//!
15//! #### Binary Search Tree Operations
16//! ```
17//! use rbt_rs::RedBlackTree;
18//!
19//! let mut rbt: RedBlackTree<i64> = (0..100).map(|x| x * x).collect();
20//!
21//! rbt.insert(-12);
22//! assert!(rbt.contains(&-12));
23//! assert_eq!(rbt.min(), Some(&-12));
24//!
25//! assert_eq!(rbt.remove(&0), Some(0));
26//! assert!(!rbt.contains(&0));
27//!
28//! assert_eq!(*rbt.min().unwrap(), -12);
29//! assert_eq!(*rbt.max().unwrap(), 99 * 99);
30//!
31//! assert_eq!(*rbt.successor(&100).unwrap(), 121);
32//! assert_eq!(*rbt.predecessor(&100).unwrap(), 81);
33//! ```
34//!
35//! #### Iteration
36//! Iterate nodes of the tree in-order (sorted), as `&T`, `&Node<T>` or `T`.
37//! ```
38//! use rbt_rs::{RedBlackTree, Node};
39//!
40//! let rbt = RedBlackTree::from_iter([5, 2, 8, 9, 1]);
41//!
42//! let first_val: Option<&i64> = rbt.iter().next();
43//! assert_eq!(first_val, Some(&1));
44//! let first_node: Option<&Node<i64>> = rbt.iter_node().next();
45//! assert_eq!(first_node.map(|x| **x), Some(1));
46//! let first_owned_val: Option<i64> = rbt.into_iter().next();
47//! assert_eq!(first_owned_val, Some(1));
48//! ```
49//!
50//! #### Subtrees
51//! Work with subtrees using the node API.
52//! ```
53//! use rbt_rs::{RedBlackTree, Node};
54//!
55//! let mut rbt: RedBlackTree<i64> = (0..100).map(|x| x * x).collect();
56//!
57//! let subtree: &Node<i64> = rbt.get_node(&144).unwrap();
58//! assert!(subtree.min().val() <= &144);
59//! assert!(subtree.max().val() >= &144);
60//!
61//! // This also allows for (on average), faster predecessor/successor operations,
62//! // since traversal starts from the node directly.
63//! let predecessor: &Node<i64> = subtree.predecessor().unwrap();
64//! assert_eq!(**predecessor, 121);
65//! assert_eq!(predecessor.successor().unwrap().val(), &144);
66//! ```
67//!
68//! #### [Tree sort](https://en.wikipedia.org/wiki/Tree_sort) in a single line đŸ˜€.
69//! Due to the Red-black tree being approximately balanced, this runs in `O(n log n)`.
70//! Though it is still not very efficient, since it requires `n` separate allocations (one per node) and it is also not in-place.
71//! ```
72//! use rbt_rs::RedBlackTree;
73//!
74//! fn treesort<T: Ord>(unsorted: impl IntoIterator<Item = T>) -> Vec<T> {
75//!     RedBlackTree::from_iter(unsorted).into_iter().collect()
76//! }
77//! ```
78
79#![feature(box_into_inner, dropck_eyepatch)]
80#![warn(missing_debug_implementations, missing_docs)]
81
82use std::{
83    borrow::Borrow,
84    fmt::{Debug, Display},
85    marker::PhantomData,
86    ops::{Deref, DerefMut},
87    ptr::NonNull,
88};
89
90use crate::{
91    Color::{Black, Red},
92    NodeKind::Sentinel,
93};
94
95/// Iterators over the nodes or values of a [RedBlackTree].
96pub mod iter;
97pub use iter::{IntoIter, Iter, IterNode};
98
99/// A [Red-black tree](https://en.wikipedia.org/wiki/Red–black_tree) which is an approximately balanced binary search tree.
100///
101/// All [`RedBlackTree`] tree binary search tree operations: [`insert`], [`remove`], [`contains`], [`min`], [`max`], [`predecessor`], [`successor`] have a worst case time complexity of `O(log n)`.
102///
103/// [`insert`]: RedBlackTree::insert
104/// [`remove`]: RedBlackTree::remove
105/// [`contains`]: RedBlackTree::contains
106/// [`min`]: RedBlackTree::min
107/// [`max`]: RedBlackTree::max
108/// [`predecessor`]: RedBlackTree::predecessor
109/// [`successor`]: RedBlackTree::successor
110pub struct RedBlackTree<T> {
111    root: NodeKind<T>,
112    len: usize,
113    // Tell the dropck that we will drop a T.
114    _owns_t: PhantomData<T>,
115}
116
117// SAFETY: We don't access the T itself.
118unsafe impl<#[may_dangle] T> Drop for RedBlackTree<T> {
119    fn drop(&mut self) {
120        self.clear();
121    }
122}
123
124impl<T> RedBlackTree<T> {
125    /// Returns an empty RedBlackTree.
126    pub fn new() -> Self {
127        Self {
128            root: NodeKind::Sentinel,
129            len: 0,
130            _owns_t: PhantomData,
131        }
132    }
133
134    /// Inserts the given value into the tree. Duplicates are permitted and will lead to duplicate values in the tree.
135    ///
136    /// This operation is `O(log n)`.
137    pub fn insert(&mut self, t: T)
138    where
139        T: Ord,
140    {
141        let mut parent = Sentinel;
142        let mut x = self.root.clone();
143        while let NodeKind::Node(node) = x.clone() {
144            parent = x;
145            if t <= node.t {
146                x = node.left.clone();
147            } else {
148                x = node.right.clone();
149            }
150        }
151
152        self.len += 1;
153        let node = match parent {
154            Sentinel => {
155                self.root = NodeKind::Node(Node::new(Sentinel, t));
156                self.root.clone().unwrap()
157            }
158            NodeKind::Node(mut parent) => {
159                if t <= parent.t {
160                    parent.left = NodeKind::Node(Node::new(NodeKind::Node(parent.clone()), t));
161                    parent.left.clone().unwrap()
162                } else {
163                    parent.right = NodeKind::Node(Node::new(NodeKind::Node(parent.clone()), t));
164                    parent.right.clone().unwrap()
165                }
166            }
167        };
168        self.insert_fixup(node);
169        assert_eq!(self.root.color(), Black);
170    }
171
172    /// Removes the first pre-order node with the given value from the tree, returning the removed value, if there was one to remove.
173    ///
174    /// This operation is `O(log n)`.
175    pub fn remove<Q>(&mut self, q: &Q) -> Option<T>
176    where
177        T: Borrow<Q>,
178        Q: Ord + Eq + ?Sized,
179    {
180        let node = self.find_nodeptr(q)?;
181        Some(self.remove_nodeptr(node))
182    }
183
184    /// Returns the minimum value, returning `None` if the tree is empty.
185    ///
186    /// This operation is `O(log n)`.
187    /// To obtain the node with the minimum value `&Node<T>` use `max_node()`.
188    pub fn min(&self) -> Option<&T> {
189        self.min_node().map(|n| &n.t)
190    }
191
192    /// Removes and returns the minimum value, returning `None` if the tree is empty.
193    ///
194    /// This operation is `O(log n)`.
195    /// If the minimum value is not unique in the tree, the first pre-order node is removed.
196    /// To obtain the value without removing it use `min()`.
197    pub fn extract_min(&mut self) -> Option<T>
198    where
199        T: Ord,
200    {
201        let NodeKind::Node(root) = self.root.clone() else {
202            return None;
203        };
204
205        let mut min = root;
206        while let NodeKind::Node(left) = min.left.clone() {
207            min = left;
208        }
209        Some(self.remove_nodeptr(min))
210    }
211
212    /// Returns the maximum value, returning `None` if the tree is empty.
213    ///
214    /// This operation is `O(log n)`.
215    /// To obtain the node with the maximum value, use `max_node()`.
216    pub fn max(&self) -> Option<&T> {
217        self.max_node().map(|n| &n.t)
218    }
219
220    /// Removes and returns the maximum value, returning `None` if the tree is empty.
221    ///
222    /// This operation is `O(log n)`.
223    /// If the maximum value is not unique in the tree, the first pre-order node is removed.
224    /// To obtain the value without removing it use `max()`.
225    pub fn extract_max(&mut self) -> Option<T>
226    where
227        T: Ord,
228    {
229        let NodeKind::Node(root) = self.root.clone() else {
230            return None;
231        };
232
233        let mut max = root;
234        while let NodeKind::Node(right) = max.right.clone() {
235            max = right;
236        }
237        Some(self.remove_nodeptr(max))
238    }
239
240    /// Returns the predecessor value, which is the previous in-order value, of the given value.
241    ///
242    /// This operation is `O(log n)`.
243    /// To obtain the predecessor node, use `get_node(t).map_or_default(|n| n.predecessor())`.
244    pub fn predecessor<'t>(&self, t: &'t T) -> Option<&T>
245    where
246        T: Ord,
247    {
248        self.get_node(t)
249            .map_or_default(|n| n.predecessor())
250            .map(|n| &n.t)
251    }
252
253    /// Returns the successor value, which is the next in-order value, of the given value.
254    ///
255    /// This operation is `O(log n)`.
256    /// To obtain the successor node, use `get_node(t).map_or_default(|n| n.successor())`.
257    pub fn successor<'t>(&self, t: &'t T) -> Option<&T>
258    where
259        T: Ord,
260    {
261        self.get_node(t)
262            .map_or_default(|n| n.successor())
263            .map(|n| &n.t)
264    }
265
266    /// Returns `true` if the tree contains the given value.
267    ///
268    /// This operation is `O(log n)`.
269    pub fn contains(&self, t: &T) -> bool
270    where
271        T: Ord,
272    {
273        self.get_node(t).is_some()
274    }
275
276    /// Removes all values from the tree.
277    ///
278    /// This operation is `O(n)` and is equivalent to dropping the tree and creating a new one.
279    pub fn clear(&mut self) {
280        let mut stack = Vec::new();
281        if let NodeKind::Node(root) = self.root.clone() {
282            stack.push(root);
283        }
284        self.root = Sentinel;
285        while let Some(mut top) = stack.pop() {
286            if let NodeKind::Node(left) = top.left.clone() {
287                stack.push(left);
288            }
289            if let NodeKind::Node(right) = top.right.clone() {
290                stack.push(right);
291            }
292            drop(unsafe { Box::from_raw(NonNull::from_mut(top.0.as_mut()).as_ptr()) });
293        }
294        self.len = 0;
295    }
296
297    /// Returns the root value of the tree.
298    ///
299    /// This operation is `O(1)`.
300    /// To obtain the root node, use `root_node()`.
301    pub fn root(&self) -> Option<&T> {
302        self.root_node().map(|ro| &ro.t)
303    }
304
305    /// Returns the number of elements in the tree.
306    pub fn len(&self) -> usize {
307        self.len
308    }
309
310    /// Returns `true` if the tree contains no elements.
311    pub fn is_empty(&self) -> bool {
312        self.len == 0
313    }
314
315    /// Returns an in-order iterator over shared references of the values in the tree.
316    ///
317    /// Iterator creation is `O(1)`.
318    pub fn iter(&self) -> Iter<'_, T> {
319        Iter {
320            iter_node: self.iter_node(),
321        }
322    }
323}
324
325impl<T> RedBlackTree<T> {
326    /// Finds the node with the given value in the tree and returns it, if it exists.
327    ///
328    /// This operation is `O(n)`.
329    /// If you only need to know whether the value exists, use `contains()`.
330    pub fn get_node<'a, Q>(&'a self, q: &Q) -> Option<&'a Node<T>>
331    where
332        T: Borrow<Q>,
333        Q: Ord + ?Sized,
334    {
335        let mut x = self.root.clone();
336        while let NodeKind::Node(node) = x {
337            match q.cmp(node.t.borrow()) {
338                std::cmp::Ordering::Less => x = node.left.clone(),
339                std::cmp::Ordering::Equal => return Some(unsafe { node.as_ref() }),
340                std::cmp::Ordering::Greater => x = node.right.clone(),
341            }
342        }
343        None
344    }
345
346    /// Returns the node with the minimum value.
347    ///
348    /// This operation is `O(log n)`.
349    /// To obtain the value directly, use `min`.
350    pub fn min_node(&self) -> Option<&Node<T>> {
351        self.root
352            .clone()
353            .node()
354            .map(|ro| unsafe { ro.as_ref() }.min())
355    }
356
357    /// Returns the node with the maximum value.
358    ///
359    /// This operation is `O(log n)`.
360    /// To obtain the value directly, use `max`.
361    pub fn max_node(&self) -> Option<&Node<T>> {
362        self.root
363            .clone()
364            .node()
365            .map(|ro| unsafe { ro.as_ref() }.max())
366    }
367
368    /// Returns the root value of the tree.
369    ///
370    /// This operation is `O(1)`.
371    pub fn root_node(&self) -> Option<&Node<T>> {
372        self.root.clone().node().map(|ro| unsafe { ro.as_ref() })
373    }
374
375    /// Returns an in-order iterator over shared references of the nodes in the tree.
376    ///
377    /// Iterator creation is `O(1)`.
378    pub fn iter_node(&self) -> IterNode<'_, T> {
379        if let NodeKind::Node(root) = self.root.clone() {
380            unsafe { root.as_ref() }.iter_node()
381        } else {
382            IterNode { stack: vec![] }
383        }
384    }
385}
386
387impl<T> RedBlackTree<T> {
388    fn find_nodeptr<Q>(&self, q: &Q) -> Option<NodePtr<T>>
389    where
390        T: Borrow<Q>,
391        Q: Ord + Eq + ?Sized,
392    {
393        let mut x = self.root.clone();
394        while let NodeKind::Node(ref node) = x {
395            match q.cmp(node.t.borrow()) {
396                std::cmp::Ordering::Less => x = node.left.clone(),
397                std::cmp::Ordering::Equal => return Some(node.clone()),
398                std::cmp::Ordering::Greater => x = node.right.clone(),
399            }
400        }
401        None
402    }
403
404    fn transplant(
405        &mut self,
406        node: NodePtr<T>,
407        mut with: NodeKind<T>,
408    ) -> (NodeKind<T>, NodeKind<T>) {
409        match node.parent() {
410            Sentinel => self.root = with.clone(),
411            NodeKind::Node(mut parent) => {
412                if parent.left.clone().map_or_default(|l| l == node) {
413                    parent.left = with.clone();
414                } else {
415                    parent.right = with.clone();
416                }
417            }
418        };
419        if let NodeKind::Node(ref mut with) = with {
420            with.p = node.parent();
421        }
422        (with, node.parent())
423    }
424
425    fn remove_nodeptr(&mut self, z: NodePtr<T>) -> T {
426        let mut y_original_color = z.color;
427
428        // If z had less than two children, replacement is the node we moved in place of z.
429        // Otherwise, replacement is the original right node of the successor of z, before we moved zs successor in place of z.
430        // It might be the sentinel, but we still need its parent for remove_fixup, so we carry it.
431        let (replacement, replacement_parent) = if z.left.is_sentinel() {
432            self.transplant(z.clone(), z.right.clone())
433        } else if z.right.is_sentinel() {
434            self.transplant(z.clone(), z.left.clone())
435        } else {
436            let mut left = z.left.clone().unwrap();
437            let mut right = z.right.clone().unwrap();
438
439            let mut successor = {
440                let mut succ = right.clone();
441                while let NodeKind::Node(left) = succ.left.clone() {
442                    succ = left;
443                }
444                succ
445            };
446            y_original_color = successor.color;
447
448            let successor_right = successor.right.clone();
449            let (replacement, replacement_parent) = if successor != right {
450                let (successor_right, successor_right_parent) =
451                    self.transplant(successor.clone(), successor_right);
452                successor.right = NodeKind::Node(right.clone());
453                right.p = NodeKind::Node(successor.clone());
454                (successor_right, successor_right_parent)
455            } else {
456                (successor_right, NodeKind::Node(successor.clone()))
457            };
458
459            self.transplant(z.clone(), NodeKind::Node(successor.clone()));
460            successor.left = NodeKind::Node(left.clone());
461            left.p = NodeKind::Node(successor.clone());
462            successor.color = z.color;
463            (replacement, replacement_parent)
464        };
465
466        if y_original_color == Black {
467            self.remove_fixup(replacement, replacement_parent);
468        };
469        self.len -= 1;
470        Box::into_inner(unsafe { Box::from_raw(z.0.as_ptr()) }).t
471    }
472
473    fn rotate_left(&mut self, mut x: NodePtr<T>) {
474        //    x
475        //  a   y
476        //     b g
477        // turns into
478        //    y
479        //  x   g
480        // a b
481
482        let mut y = x.right.clone().unwrap();
483
484        // x.right points to y.left and y.left to x
485        x.right = y.left.clone();
486        if let NodeKind::Node(ref mut y_left) = y.left {
487            y_left.p = NodeKind::Node(x.clone());
488        }
489
490        // x.p.{left/right} points to y instead of x
491        // y.p points to x.p
492        if let NodeKind::Node(mut x_parent) = x.p.clone() {
493            if x_parent.left.clone().map_or_default(|l| l == x) {
494                x_parent.left = NodeKind::Node(y.clone());
495            } else {
496                x_parent.right = NodeKind::Node(y.clone());
497            }
498        } else {
499            self.root = NodeKind::Node(y.clone());
500        }
501        y.p = x.p.clone();
502
503        // y.left points to x and x.p to y
504        y.left = NodeKind::Node(x.clone());
505        x.p = NodeKind::Node(y);
506    }
507
508    fn rotate_right(&mut self, mut y: NodePtr<T>) {
509        //    y
510        //  x   g
511        // a b
512        // turns into
513        //    x
514        //  a   y
515        //     b g
516
517        let mut x = y.left.clone().unwrap();
518
519        // y.left points to x.right and y.right to x
520        y.left = x.right.clone();
521        if let NodeKind::Node(ref mut x_right) = x.right {
522            x_right.p = NodeKind::Node(y.clone());
523        }
524
525        // y.p.{left/right} points to x instead of y
526        // x.p points to y.p
527        if let NodeKind::Node(mut y_parent) = y.p.clone() {
528            if y_parent.left.clone().map_or_default(|l| l == y) {
529                y_parent.left = NodeKind::Node(x.clone());
530            } else {
531                y_parent.right = NodeKind::Node(x.clone());
532            }
533        } else {
534            self.root = NodeKind::Node(x.clone());
535        }
536        x.p = y.p.clone();
537
538        // x.right points to y and y.p to x
539        x.right = NodeKind::Node(y.clone());
540        y.p = NodeKind::Node(x);
541    }
542
543    fn insert_fixup(&mut self, mut node: NodePtr<T>) {
544        while node.p.color() == Red {
545            // If the parent is red, it can't be the sentinel.
546            let mut parent = node.parent().unwrap();
547            // It can also not be the root, since the root is black, so the grandparent must exist.
548            let mut grandparent = node.grandparent().unwrap();
549
550            if grandparent.left.clone().map_or_default(|l| l == parent) {
551                let uncle = grandparent.right.clone();
552                // case 1
553                if uncle.color() == Red {
554                    parent.color = Black;
555                    // If the uncle is red, it must not be the sentinel.
556                    uncle.unwrap().color = Black;
557                    grandparent.color = Red;
558                    node = grandparent;
559                } else {
560                    // case 2
561                    if parent.right.clone().map_or_default(|r| r == node) {
562                        node = parent;
563                        self.rotate_left(node.clone());
564                    }
565                    // case 3
566                    node.parent().unwrap().color = Black;
567                    node.grandparent().unwrap().color = Red;
568                    self.rotate_right(node.grandparent().unwrap());
569                }
570            } else {
571                let uncle = grandparent.left.clone();
572                if uncle.color() == Red {
573                    parent.color = Black;
574                    // If the uncle is red, it must not be the sentinel.
575                    uncle.unwrap().color = Black;
576                    grandparent.color = Red;
577                    node = grandparent;
578                } else {
579                    if parent.left.clone().map_or_default(|l| l == node) {
580                        node = parent;
581                        self.rotate_right(node.clone());
582                    }
583                    node.parent().unwrap().color = Black;
584                    node.grandparent().unwrap().color = Red;
585                    self.rotate_left(node.grandparent().unwrap());
586                }
587            }
588        }
589
590        self.root.clone().unwrap().color = Black;
591    }
592
593    fn remove_fixup(&mut self, mut node: NodeKind<T>, mut parent_outer: NodeKind<T>) {
594        while node.color() == Black && self.root != node {
595            // Node is not the root, so its parent must exist.
596            let mut parent = parent_outer.clone().unwrap();
597            if parent.left == node {
598                // Node is doubly black, so its sibling cannot be the sentinel, since that would violate the simple path property.
599                let mut sibling = parent.right.clone().unwrap();
600                // case 1
601                if sibling.color == Red {
602                    sibling.color = Black;
603                    parent.color = Red;
604                    self.rotate_left(parent.clone());
605                    sibling = parent.right.clone().unwrap();
606                }
607                // case 2
608                if sibling.left.color() == Black && sibling.right.color() == Black {
609                    sibling.color = Red;
610                    node = NodeKind::Node(parent.clone());
611                    parent_outer = parent.p.clone();
612                } else {
613                    // case 3
614                    if sibling.right.color() == Black {
615                        sibling.left.clone().unwrap().color = Red;
616                        sibling.color = Red;
617                        self.rotate_right(sibling);
618                        sibling = parent.right.clone().unwrap();
619                    }
620                    // case 4
621                    sibling.color = parent.color;
622                    parent.color = Black;
623                    sibling.right.clone().unwrap().color = Black;
624                    self.rotate_left(parent);
625                    node = self.root.clone();
626                }
627            } else {
628                // Node is doubly black, so its sibling cannot be the sentinel, since that would violate the simple path property.
629                let mut sibling = parent.left.clone().unwrap();
630                // case 1
631                if sibling.color == Red {
632                    sibling.color = Black;
633                    parent.color = Red;
634                    self.rotate_right(parent.clone());
635                    sibling = parent.left.clone().unwrap();
636                }
637                // case 2
638                if sibling.right.color() == Black && sibling.left.color() == Black {
639                    sibling.color = Red;
640                    node = NodeKind::Node(parent.clone());
641                    parent_outer = parent.p.clone();
642                } else {
643                    // case 3
644                    if sibling.left.color() == Black {
645                        sibling.right.clone().unwrap().color = Red;
646                        sibling.color = Red;
647                        self.rotate_left(sibling);
648                        sibling = parent.left.clone().unwrap();
649                    }
650                    // case 4
651                    sibling.color = parent.color;
652                    parent.color = Black;
653                    sibling.left.clone().unwrap().color = Black;
654                    self.rotate_right(parent);
655                    node = self.root.clone();
656                }
657            }
658        }
659        if let NodeKind::Node(mut x) = node {
660            x.color = Black;
661        }
662    }
663}
664
665impl<T> Default for RedBlackTree<T> {
666    fn default() -> Self {
667        Self::new()
668    }
669}
670
671// SAFETY: The nodes are allocated via Box, which is Send if T: Send.
672unsafe impl<T: Send> Send for RedBlackTree<T> {}
673// SAFETY: There is no interior mutability of T.
674// Mutation requires &mut RedBlackTree, so &T can be shared accross threads.
675unsafe impl<T: Sync> Sync for RedBlackTree<T> {}
676
677impl<T: Clone> Clone for RedBlackTree<T> {
678    fn clone(&self) -> Self {
679        let NodeKind::Node(root) = self.root.clone() else {
680            return Self::new();
681        };
682
683        fn clone_node<T: Clone>(p: NodeKind<T>, node: &Node<T>) -> NodeKind<T> {
684            let mut new = Node::as_node_ptr(Node {
685                p,
686                t: node.t.clone(),
687                left: Sentinel,
688                right: Sentinel,
689                color: node.color,
690            });
691            new.left = node
692                .left
693                .clone()
694                .map_or_default(|l| clone_node(NodeKind::Node(new.clone()), &l));
695            new.right = node
696                .right
697                .clone()
698                .map_or_default(|r| clone_node(NodeKind::Node(new.clone()), &r));
699            NodeKind::Node(new)
700        }
701
702        let root = clone_node(Sentinel, &root);
703        Self {
704            len: self.len,
705            root: root,
706            _owns_t: PhantomData,
707        }
708    }
709}
710
711impl<T: PartialEq> PartialEq for RedBlackTree<T> {
712    fn eq(&self, other: &Self) -> bool {
713        self.iter().eq(other.iter())
714    }
715}
716
717impl<T: Eq> Eq for RedBlackTree<T> {}
718
719impl<T: Display> Display for RedBlackTree<T> {
720    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
721        write!(
722            f,
723            "RedBlackTree({})",
724            self.root
725                .clone()
726                .map_or_default(|ro| format!("{}", unsafe { ro.as_ref() }))
727        )
728    }
729}
730
731impl<T: Debug> Debug for RedBlackTree<T> {
732    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
733        f.debug_struct("RedBlackTree")
734            .field(
735                "root",
736                &self
737                    .root
738                    .clone()
739                    .map_or_default(|ro| format!("{:?}", unsafe { ro.as_ref() })),
740            )
741            .field("len", &self.len)
742            .finish()
743    }
744}
745
746impl<A: Ord> Extend<A> for RedBlackTree<A> {
747    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
748        for t in iter {
749            self.insert(t);
750        }
751    }
752}
753
754impl<A: Ord> FromIterator<A> for RedBlackTree<A> {
755    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
756        let mut rbt = RedBlackTree::new();
757        for t in iter {
758            rbt.insert(t);
759        }
760        rbt
761    }
762}
763
764/// A node in a [RedBlackTree].
765///
766/// The only publically available field is the contained value `t`, which can also be obtained through `val()`.
767/// `Node<T>` implements `Deref<Target = T>`, so you can use `&Node<T>` in place of `&T` through deref-coercion.
768pub struct Node<T> {
769    p: NodeKind<T>,
770    /// The value contained in the Node.
771    pub t: T,
772    left: NodeKind<T>,
773    right: NodeKind<T>,
774    color: Color,
775}
776
777impl<T> Node<T> {
778    /// Returns a shared reference to the value contained in the node.
779    pub fn val(&self) -> &T {
780        &self.t
781    }
782
783    /// Returns the minimum value in this subtree.
784    ///
785    /// This operation is `O(log n)`.
786    pub fn min(&self) -> &Node<T> {
787        let mut x = self;
788        while let NodeKind::Node(left) = x.left.clone() {
789            x = unsafe { left.as_ref() };
790        }
791        x
792    }
793
794    /// Returns the maximum value in this subtree.
795    ///
796    /// This operation is `O(log n)`.
797    pub fn max(&self) -> &Node<T> {
798        let mut x = self;
799        while let NodeKind::Node(right) = x.right.clone() {
800            x = unsafe { right.as_ref() };
801        }
802        x
803    }
804
805    /// Returns the predecessor node, which is the previous in-order node and is not necessarily within the sub-tree defined by the current node.
806    ///
807    /// This operation is at-worst `O(log n)`.
808    pub fn predecessor(&self) -> Option<&Node<T>> {
809        match self.left {
810            NodeKind::Node(ref left) => Some(Node::max(left)),
811            Sentinel => {
812                // If we dont have a left subtree, there are two options:
813                // 1. If we, or one of our ancestors, forms a right-subtree, then that ancestor is the predecessor.
814                //    This will also be first ancestor that has a value <= us.
815                // 2. If we are in no right-subtrees, we are the smallest node in the tree and have no predecessor.
816                let mut x = self;
817                while let NodeKind::Node(p) = x.p.clone() {
818                    if p.right
819                        .clone()
820                        .map_or_default(|r| r == NodePtr(NonNull::from_ref(x)))
821                    {
822                        return Some(unsafe { p.as_ref() });
823                    }
824                    x = unsafe { p.as_ref() };
825                }
826                None
827            }
828        }
829    }
830
831    /// Returns the successor node, which is the previous in-order node and is not necessarily within the sub-tree defined by the current node.
832    ///
833    /// This operation is at-worst `O(log n)`.
834    pub fn successor(&self) -> Option<&Node<T>> {
835        match self.right {
836            NodeKind::Node(ref right) => Some(Node::min(right)),
837            Sentinel => {
838                // If we dont have a right subtree, there are two options:
839                // 1. If we are, or one of our ancestors, forms a left-subtree, then that ancestor is the successor.
840                //    This will also be the first ancestor that has a value > us.
841                // 2. If we are in no left-subtrees, we are the largest node in the tree and have no successor.
842                let mut x = self;
843                while let NodeKind::Node(p) = x.p.clone() {
844                    if p.left
845                        .clone()
846                        .map_or_default(|l| l == NodePtr(NonNull::from_ref(x)))
847                    {
848                        return Some(unsafe { p.as_ref() });
849                    }
850                    x = unsafe { p.as_ref() };
851                }
852
853                None
854            }
855        }
856    }
857
858    /// Returns an in-order iterator over shared references of the values in this sub-tree.
859    ///
860    /// Iterator creation is `O(1)`.
861    pub fn iter(&self) -> Iter<'_, T> {
862        Iter {
863            iter_node: self.iter_node(),
864        }
865    }
866
867    /// Returns an in-order iterator over shared references of the nodes in this sub-tree.
868    ///
869    /// Iterator creation is `O(1)`.
870    pub fn iter_node(&self) -> IterNode<'_, T> {
871        IterNode {
872            stack: vec![(self, false)],
873        }
874    }
875}
876
877impl<T> Node<T> {
878    fn new(p: NodeKind<T>, t: T) -> NodePtr<T> {
879        Node::as_node_ptr(Self {
880            left: Sentinel,
881            right: Sentinel,
882            p,
883            t,
884            color: Red,
885        })
886    }
887
888    fn as_node_ptr(node: Node<T>) -> NodePtr<T> {
889        NodePtr(NonNull::new(Box::into_raw(Box::new(node))).expect("allocate node"))
890    }
891
892    fn parent(&self) -> NodeKind<T> {
893        self.p.clone()
894    }
895
896    fn grandparent(&self) -> NodeKind<T> {
897        self.p.clone().map_or_default(|p| p.parent())
898    }
899}
900
901impl<T> Deref for Node<T> {
902    type Target = T;
903
904    fn deref(&self) -> &Self::Target {
905        &self.t
906    }
907}
908
909impl<T: PartialEq> PartialEq for Node<T> {
910    fn eq(&self, other: &Self) -> bool {
911        self.t == other.t
912    }
913}
914
915impl<T: Eq> Eq for Node<T> {}
916
917impl<T: Ord> Ord for Node<T> {
918    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
919        self.t.cmp(&other.t)
920    }
921}
922
923impl<T: Ord> PartialOrd for Node<T> {
924    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
925        Some(self.cmp(other))
926    }
927}
928
929impl<T: Display> Display for Node<T> {
930    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
931        if let NodeKind::Node(ref left) = self.left {
932            write!(f, "({})", unsafe { left.as_ref() })?;
933        }
934        write!(f, " {} ", self.t)?;
935        if let NodeKind::Node(ref right) = self.right {
936            write!(f, "({})", unsafe { right.as_ref() })?;
937        }
938        Ok(())
939    }
940}
941
942impl<T: Debug> Debug for Node<T> {
943    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
944        if let NodeKind::Node(ref left) = self.left {
945            write!(f, "({:?})", left)?;
946        }
947        write!(f, " <{:?}, {:?}> ", self.t, self.color)?;
948        if let NodeKind::Node(ref right) = self.right {
949            write!(f, "({:?})", right)?;
950        }
951        Ok(())
952    }
953}
954
955struct NodePtr<T>(NonNull<Node<T>>);
956
957impl<T> PartialEq for NodePtr<T> {
958    fn eq(&self, other: &Self) -> bool {
959        self.0 == other.0
960    }
961}
962
963impl<T> Eq for NodePtr<T> {}
964
965impl<T> Clone for NodePtr<T> {
966    fn clone(&self) -> Self {
967        Self(self.0.clone())
968    }
969}
970
971impl<T> DerefMut for NodePtr<T> {
972    fn deref_mut(&mut self) -> &mut Self::Target {
973        unsafe { self.0.as_mut() }
974    }
975}
976
977impl<T> Deref for NodePtr<T> {
978    type Target = Node<T>;
979
980    fn deref(&self) -> &Self::Target {
981        unsafe { self.0.as_ref() }
982    }
983}
984
985impl<T: Debug> Debug for NodePtr<T> {
986    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
987        write!(f, "{:?}", unsafe { self.0.as_ref() })
988    }
989}
990
991impl<T> NodePtr<T> {
992    /// Returns the NodePtr as a reference with arbitrary lifetime.
993    /// Invariant: The caller must ensure that the lifetime is tied to a shared reference to the tree.
994    unsafe fn as_ref<'a>(&self) -> &'a Node<T> {
995        // SAFETY: If the caller upholds the invariant, the reference cannot be stale and we cannot violate aliasing rules, since deallocating a node requires &mut RedBlackTree.
996        // The reference is guaranteed to be aligned and non-null, since it the backing Node<T> was allocated using Box::new.
997        unsafe { self.0.as_ref() }
998    }
999}
1000
1001#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1002enum Color {
1003    Red,
1004    Black,
1005}
1006
1007#[derive(Debug, Default)]
1008enum NodeKind<T> {
1009    #[default]
1010    Sentinel,
1011    Node(NodePtr<T>),
1012}
1013
1014impl<T> NodeKind<T> {
1015    fn color(&self) -> Color {
1016        match self {
1017            NodeKind::Sentinel => Black,
1018            NodeKind::Node(node) => node.color,
1019        }
1020    }
1021
1022    fn is_sentinel(&self) -> bool {
1023        match self {
1024            Sentinel => true,
1025            NodeKind::Node(_) => false,
1026        }
1027    }
1028
1029    /// Equivalent to Result::ok.
1030    fn node(self) -> Option<NodePtr<T>> {
1031        match self {
1032            Sentinel => None,
1033            NodeKind::Node(node) => Some(node),
1034        }
1035    }
1036
1037    fn map_or_default<U: Default>(self, f: impl FnOnce(NodePtr<T>) -> U) -> U {
1038        match self {
1039            Sentinel => U::default(),
1040            NodeKind::Node(node) => f(node),
1041        }
1042    }
1043
1044    fn unwrap(self) -> NodePtr<T> {
1045        match self {
1046            Sentinel => panic!("expected Node, but got Sentinel"),
1047            NodeKind::Node(node) => node,
1048        }
1049    }
1050}
1051
1052impl<T> Clone for NodeKind<T> {
1053    fn clone(&self) -> Self {
1054        match self {
1055            Self::Sentinel => Self::Sentinel,
1056            Self::Node(node_ptr) => Self::Node(node_ptr.clone()),
1057        }
1058    }
1059}
1060
1061impl<T> PartialEq for NodeKind<T> {
1062    fn eq(&self, other: &Self) -> bool {
1063        match (self, other) {
1064            (Self::Node(l), Self::Node(r)) => l == r,
1065            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
1066        }
1067    }
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072
1073    mod rbt {
1074        use super::super::*;
1075        use std::collections::VecDeque;
1076
1077        fn assert_tree_equal<T: PartialEq + Debug + Clone>(
1078            tree: &RedBlackTree<T>,
1079            want: &[&[Option<(T, Color)>]],
1080        ) {
1081            let mut queue = VecDeque::new();
1082            queue.push_back(tree.root.clone());
1083
1084            let mut d = 0;
1085            while !queue.is_empty() {
1086                let mut level = Vec::with_capacity(2usize.pow(d as u32) as usize);
1087                for _ in 0..queue.len() {
1088                    let front = queue.pop_front().unwrap().node();
1089                    level.push(front.as_ref().map(|f| (f.t.clone(), f.color)));
1090                    if let Some(front) = front.clone() {
1091                        queue.push_back(front.left.clone());
1092                        queue.push_back(front.right.clone());
1093                    }
1094                }
1095                if d >= want.len() {
1096                    return;
1097                }
1098                assert_eq!(&level, want[d]);
1099                d += 1;
1100            }
1101        }
1102
1103        #[test]
1104        fn insert_with_all_fixup_cases() {
1105            let mut rbt = RedBlackTree::from_iter([11, 2, 14, 1, 7, 15, 5, 8]);
1106            #[rustfmt::skip]
1107            assert_tree_equal(
1108                &rbt,
1109                &[
1110                    &[Some((11, Black))],
1111                    &[Some((2, Red)), Some((14, Black))],
1112                    &[Some((1, Black)), Some((7, Black)), None, Some((15, Red))],
1113                    &[None, None, Some((5, Red)), Some((8, Red)), None, None],
1114                ],
1115            );
1116
1117            // when
1118            rbt.insert(4);
1119
1120            // then
1121            #[rustfmt::skip]
1122            assert_tree_equal(
1123                &rbt,
1124                &[
1125                    &[Some((7, Black))],
1126                    &[Some((2, Red)), Some((11, Red))],
1127                    &[Some((1, Black)), Some((5, Black)), Some((8, Black)), Some((14, Black))],
1128                    &[None, None, Some((4, Red)), None, None, None, None, Some((15, Red))],
1129                ],
1130            );
1131            assert_eq!(rbt.root.color(), Black);
1132        }
1133
1134        #[test]
1135        fn clear() {
1136            // This test is mostly interesting to see that we don't leak with miri.
1137            let mut rbt = RedBlackTree::from_iter([2, 4]);
1138            rbt.clear();
1139            assert!(rbt.is_empty());
1140        }
1141    }
1142
1143    mod node {
1144        use super::super::*;
1145
1146        #[test]
1147        fn successor_has_right() {
1148            let rbt = RedBlackTree::from_iter([2, 4, 3]);
1149            let four = rbt.get_node(&2).unwrap();
1150            assert_eq!(four.successor().map(|s| s.t), Some(3));
1151        }
1152
1153        #[test]
1154        fn successor_largest() {
1155            let rbt = RedBlackTree::from_iter([4, 3, 5]);
1156            let four = rbt.get_node(&5).unwrap();
1157            assert_eq!(four.successor().map(|s| s.t), None);
1158        }
1159
1160        #[test]
1161        fn successor_left_subtree_immediate() {
1162            let rbt = RedBlackTree::from_iter([5, 3]);
1163            let four = rbt.get_node(&3).unwrap();
1164            assert_eq!(four.successor().map(|s| s.t), Some(5));
1165        }
1166
1167        #[test]
1168        fn successor_left_subtree_ancestor() {
1169            let rbt = RedBlackTree::from_iter([5, 3, 4]);
1170            let four = rbt.get_node(&4).unwrap();
1171            assert_eq!(four.successor().map(|s| s.t), Some(5));
1172        }
1173
1174        #[test]
1175        fn predecessor_has_left() {
1176            let rbt = RedBlackTree::from_iter([4, 3, 2]);
1177            let four = rbt.get_node(&3).unwrap();
1178            assert_eq!(four.predecessor().map(|s| s.t), Some(2));
1179        }
1180
1181        #[test]
1182        fn predecessor_smallest() {
1183            let rbt = RedBlackTree::from_iter([4, 3, 2]);
1184            let four = rbt.get_node(&2).unwrap();
1185            assert_eq!(four.predecessor().map(|s| s.t), None);
1186        }
1187
1188        #[test]
1189        fn predecessor_right_subtree_immediate() {
1190            let rbt = RedBlackTree::from_iter([4, 5]);
1191            let four = rbt.get_node(&5).unwrap();
1192            assert_eq!(four.predecessor().map(|s| s.t), Some(4));
1193        }
1194
1195        #[test]
1196        fn predecessor_right_subtree_ancestor() {
1197            let rbt = RedBlackTree::from_iter([1, 3, 2]);
1198            let four = rbt.get_node(&2).unwrap();
1199            assert_eq!(four.predecessor().map(|s| s.t), Some(1));
1200        }
1201    }
1202
1203    mod quickcheck {
1204        use super::super::*;
1205        use quickcheck::QuickCheck;
1206        use rand::seq::SliceRandom;
1207
1208        fn rbt_property(rbt: &RedBlackTree<i64>) -> bool {
1209            fn dfs(node: NodeKind<i64>, le: i64, ge: i64) -> bool {
1210                if let NodeKind::Node(node) = node {
1211                    if node.t > le || node.t < ge {
1212                        return false;
1213                    }
1214                    dfs(node.left.clone(), node.t, ge) && dfs(node.right.clone(), le, node.t)
1215                } else {
1216                    true
1217                }
1218            }
1219            dfs(rbt.root.clone(), i64::MAX, i64::MIN)
1220        }
1221
1222        fn rb_property_root_is_black(rbt: &RedBlackTree<i64>) -> bool {
1223            rbt.root.color() == Black
1224        }
1225
1226        fn rb_property_red_parent_has_black_children(rbt: &RedBlackTree<i64>) -> bool {
1227            fn dfs(node: NodeKind<i64>) -> bool {
1228                match node {
1229                    Sentinel => true,
1230                    NodeKind::Node(node) => {
1231                        if node.color == Red
1232                            && !(node.left.color() == Black && node.right.color() == Black)
1233                        {
1234                            return false;
1235                        }
1236                        dfs(node.left.clone()) && dfs(node.right.clone())
1237                    }
1238                }
1239            }
1240            dfs(rbt.root.clone())
1241        }
1242
1243        fn rb_property_black_height_of_simple_paths(rbt: &RedBlackTree<i64>) -> bool {
1244            fn black_height(node: NodeKind<i64>) -> (usize, bool) {
1245                match node {
1246                    Sentinel => (1, true),
1247                    NodeKind::Node(node) => {
1248                        let (left, lok) = black_height(node.left.clone());
1249                        let (_, rok) = black_height(node.right.clone());
1250                        if node.color == Black {
1251                            (left + 1, lok && rok)
1252                        } else {
1253                            (left, lok && rok)
1254                        }
1255                    }
1256                }
1257            }
1258            black_height(rbt.root.clone()).1
1259        }
1260
1261        fn rb_lg_height(rbt: &RedBlackTree<i64>) -> bool {
1262            fn max_edge_count(node: NodeKind<i64>) -> u32 {
1263                match node {
1264                    Sentinel => 1,
1265                    NodeKind::Node(node) => {
1266                        max_edge_count(node.left.clone()).max(max_edge_count(node.right.clone()))
1267                            + 1
1268                    }
1269                }
1270            }
1271            let height = max_edge_count(rbt.root.clone()) - 1;
1272            let maximum_expected = 2 * (rbt.len + 1).ilog2();
1273            height <= maximum_expected
1274        }
1275
1276        fn all_rb_properties(rbt: &RedBlackTree<i64>) -> bool {
1277            rbt_property(rbt)
1278                && rb_property_root_is_black(rbt)
1279                && rb_property_red_parent_has_black_children(rbt)
1280                && rb_property_black_height_of_simple_paths(rbt)
1281                && rb_lg_height(rbt)
1282        }
1283
1284        fn min(values: Vec<i64>) -> bool {
1285            let rbt = RedBlackTree::from_iter(values);
1286            let rbt_min = rbt.min_node().map(|n| n.t);
1287            let min_iter = rbt.iter_node().map(|n| n.t).min();
1288            rbt_min == min_iter
1289        }
1290
1291        fn max(values: Vec<i64>) -> bool {
1292            let rbt = RedBlackTree::from_iter(values);
1293            let rbt_max = rbt.max_node().map(|n| n.t);
1294            let max_iter = rbt.iter_node().map(|n| n.t).max();
1295            rbt_max == max_iter
1296        }
1297
1298        fn clone_works(values: Vec<i64>) -> bool {
1299            let rbt = RedBlackTree::from_iter(values);
1300            let clone = rbt.clone();
1301            fn dfs(lhs: NodeKind<i64>, rhs: NodeKind<i64>) -> bool {
1302                match (lhs, rhs) {
1303                    (Sentinel, Sentinel) => true,
1304                    (Sentinel, NodeKind::Node(_)) => false,
1305                    (NodeKind::Node(_), Sentinel) => false,
1306                    (NodeKind::Node(lhs), NodeKind::Node(rhs)) => {
1307                        if !lhs.t == rhs.t {
1308                            return false;
1309                        }
1310                        // Pointers should never be equal.
1311                        if lhs == rhs {
1312                            return false;
1313                        }
1314                        dfs(lhs.left.clone(), rhs.left.clone())
1315                            && dfs(lhs.right.clone(), rhs.right.clone())
1316                    }
1317                }
1318            }
1319            dfs(rbt.root.clone(), clone.root.clone())
1320        }
1321
1322        fn insert_upholds_properties(values: Vec<i64>) -> bool {
1323            let rbt = RedBlackTree::from_iter(values.clone());
1324            all_rb_properties(&rbt)
1325                && rbt.len == values.len()
1326                && values.into_iter().all(|v| rbt.contains(&v))
1327        }
1328
1329        fn remove_upholds_properties(mut values: Vec<i64>) -> bool {
1330            let mut rbt = RedBlackTree::from_iter(values.clone());
1331            values.shuffle(&mut rand::rng());
1332
1333            for v in values.iter() {
1334                if !rbt.remove(&v).is_some_and(|x| x == *v) {
1335                    return false;
1336                }
1337                if !all_rb_properties(&rbt) {
1338                    return false;
1339                }
1340            }
1341
1342            true
1343        }
1344
1345        fn insert_remove_interleaved_upholds_properties(mut values: Vec<i64>) -> bool {
1346            let mut rbt = RedBlackTree::from_iter(values.clone());
1347            values.shuffle(&mut rand::rng());
1348
1349            for v in values.iter() {
1350                if !rbt.remove(&v).is_some_and(|x| x == *v) {
1351                    return false;
1352                }
1353                if !all_rb_properties(&rbt) {
1354                    return false;
1355                }
1356
1357                rbt.insert(rand::random());
1358                if !all_rb_properties(&rbt) {
1359                    return false;
1360                }
1361            }
1362
1363            true
1364        }
1365
1366        fn extract_min_works(mut values: Vec<i64>) -> bool {
1367            let mut rbt = RedBlackTree::from_iter(values.iter().cloned());
1368            values.sort();
1369            for v in values {
1370                if rbt.extract_min().is_none_or(|min| min != v) {
1371                    return false;
1372                }
1373
1374                if !all_rb_properties(&rbt) {
1375                    return false;
1376                }
1377            }
1378
1379            rbt.extract_min().is_none()
1380        }
1381
1382        fn extract_max_works(mut values: Vec<i64>) -> bool {
1383            let mut rbt = RedBlackTree::from_iter(values.iter().cloned());
1384            values.sort_by(|l, r| std::cmp::Reverse(l).cmp(&std::cmp::Reverse(r)));
1385            for v in values {
1386                if rbt.extract_max().is_none_or(|max| max != v) {
1387                    return false;
1388                }
1389
1390                if !all_rb_properties(&rbt) {
1391                    return false;
1392                }
1393            }
1394
1395            rbt.extract_max().is_none()
1396        }
1397
1398        #[test]
1399        fn quickcheck() {
1400            let mut qc = QuickCheck::new().tests(cfg_select!(miri => 10, _ => 1000));
1401            // RedBlackTree
1402            qc.quickcheck(min as fn(Vec<i64>) -> bool);
1403            qc.quickcheck(max as fn(Vec<i64>) -> bool);
1404            qc.quickcheck(clone_works as fn(Vec<i64>) -> bool);
1405            qc.quickcheck(insert_upholds_properties as fn(Vec<i64>) -> bool);
1406            qc.quickcheck(remove_upholds_properties as fn(Vec<i64>) -> bool);
1407            qc.quickcheck(insert_remove_interleaved_upholds_properties as fn(Vec<i64>) -> bool);
1408            qc.quickcheck(extract_min_works as fn(Vec<i64>) -> bool);
1409            qc.quickcheck(extract_max_works as fn(Vec<i64>) -> bool);
1410        }
1411    }
1412}