1 // SPDX-License-Identifier: GPL-2.0
5 //! C header: [`include/linux/rbtree.h`](srctree/include/linux/rbtree.h)
7 //! Reference: <https://docs.kernel.org/core-api/rbtree.html>
9 use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::*};
14 ptr::{addr_of_mut, from_mut, NonNull},
17 /// A red-black tree with owned nodes.
19 /// It is backed by the kernel C red-black trees.
23 /// In the example below we do several operations on a tree. We note that insertions may fail if
24 /// the system is out of memory.
27 /// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode, RBTreeNodeReservation}};
29 /// // Create a new tree.
30 /// let mut tree = RBTree::new();
32 /// // Insert three elements.
33 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
34 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
35 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
37 /// // Check the nodes we just inserted.
39 /// assert_eq!(tree.get(&10).unwrap(), &100);
40 /// assert_eq!(tree.get(&20).unwrap(), &200);
41 /// assert_eq!(tree.get(&30).unwrap(), &300);
44 /// // Iterate over the nodes we just inserted.
46 /// let mut iter = tree.iter();
47 /// assert_eq!(iter.next().unwrap(), (&10, &100));
48 /// assert_eq!(iter.next().unwrap(), (&20, &200));
49 /// assert_eq!(iter.next().unwrap(), (&30, &300));
50 /// assert!(iter.next().is_none());
53 /// // Print all elements.
54 /// for (key, value) in &tree {
55 /// pr_info!("{} = {}\n", key, value);
58 /// // Replace one of the elements.
59 /// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?;
61 /// // Check that the tree reflects the replacement.
63 /// let mut iter = tree.iter();
64 /// assert_eq!(iter.next().unwrap(), (&10, &1000));
65 /// assert_eq!(iter.next().unwrap(), (&20, &200));
66 /// assert_eq!(iter.next().unwrap(), (&30, &300));
67 /// assert!(iter.next().is_none());
70 /// // Change the value of one of the elements.
71 /// *tree.get_mut(&30).unwrap() = 3000;
73 /// // Check that the tree reflects the update.
75 /// let mut iter = tree.iter();
76 /// assert_eq!(iter.next().unwrap(), (&10, &1000));
77 /// assert_eq!(iter.next().unwrap(), (&20, &200));
78 /// assert_eq!(iter.next().unwrap(), (&30, &3000));
79 /// assert!(iter.next().is_none());
82 /// // Remove an element.
85 /// // Check that the tree reflects the removal.
87 /// let mut iter = tree.iter();
88 /// assert_eq!(iter.next().unwrap(), (&20, &200));
89 /// assert_eq!(iter.next().unwrap(), (&30, &3000));
90 /// assert!(iter.next().is_none());
93 /// # Ok::<(), Error>(())
96 /// In the example below, we first allocate a node, acquire a spinlock, then insert the node into
97 /// the tree. This is useful when the insertion context does not allow sleeping, for example, when
98 /// holding a spinlock.
101 /// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode}, sync::SpinLock};
103 /// fn insert_test(tree: &SpinLock<RBTree<u32, u32>>) -> Result {
104 /// // Pre-allocate node. This may fail (as it allocates memory).
105 /// let node = RBTreeNode::new(10, 100, flags::GFP_KERNEL)?;
107 /// // Insert node while holding the lock. It is guaranteed to succeed with no allocation
109 /// let mut guard = tree.lock();
110 /// guard.insert(node);
115 /// In the example below, we reuse an existing node allocation from an element we removed.
118 /// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNodeReservation}};
120 /// // Create a new tree.
121 /// let mut tree = RBTree::new();
123 /// // Insert three elements.
124 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
125 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
126 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
128 /// // Check the nodes we just inserted.
130 /// let mut iter = tree.iter();
131 /// assert_eq!(iter.next().unwrap(), (&10, &100));
132 /// assert_eq!(iter.next().unwrap(), (&20, &200));
133 /// assert_eq!(iter.next().unwrap(), (&30, &300));
134 /// assert!(iter.next().is_none());
137 /// // Remove a node, getting back ownership of it.
138 /// let existing = tree.remove(&30).unwrap();
140 /// // Check that the tree reflects the removal.
142 /// let mut iter = tree.iter();
143 /// assert_eq!(iter.next().unwrap(), (&10, &100));
144 /// assert_eq!(iter.next().unwrap(), (&20, &200));
145 /// assert!(iter.next().is_none());
148 /// // Create a preallocated reservation that we can re-use later.
149 /// let reservation = RBTreeNodeReservation::new(flags::GFP_KERNEL)?;
151 /// // Insert a new node into the tree, reusing the previous allocation. This is guaranteed to
152 /// // succeed (no memory allocations).
153 /// tree.insert(reservation.into_node(15, 150));
155 /// // Check that the tree reflect the new insertion.
157 /// let mut iter = tree.iter();
158 /// assert_eq!(iter.next().unwrap(), (&10, &100));
159 /// assert_eq!(iter.next().unwrap(), (&15, &150));
160 /// assert_eq!(iter.next().unwrap(), (&20, &200));
161 /// assert!(iter.next().is_none());
164 /// # Ok::<(), Error>(())
169 /// Non-null parent/children pointers stored in instances of the `rb_node` C struct are always
170 /// valid, and pointing to a field of our internal representation of a node.
171 pub struct RBTree<K, V> {
172 root: bindings::rb_root,
173 _p: PhantomData<Node<K, V>>,
176 // SAFETY: An [`RBTree`] allows the same kinds of access to its values that a struct allows to its
177 // fields, so we use the same Send condition as would be used for a struct with K and V fields.
178 unsafe impl<K: Send, V: Send> Send for RBTree<K, V> {}
180 // SAFETY: An [`RBTree`] allows the same kinds of access to its values that a struct allows to its
181 // fields, so we use the same Sync condition as would be used for a struct with K and V fields.
182 unsafe impl<K: Sync, V: Sync> Sync for RBTree<K, V> {}
184 impl<K, V> RBTree<K, V> {
185 /// Creates a new and empty tree.
186 pub fn new() -> Self {
188 // INVARIANT: There are no nodes in the tree, so the invariant holds vacuously.
189 root: bindings::rb_root::default(),
194 /// Returns an iterator over the tree nodes, sorted by key.
195 pub fn iter(&self) -> Iter<'_, K, V> {
199 // - `self.root` is a valid pointer to a tree root.
200 // - `bindings::rb_first` produces a valid pointer to a node given `root` is valid.
202 // SAFETY: by the invariants, all pointers are valid.
203 next: unsafe { bindings::rb_first(&self.root) },
204 _phantom: PhantomData,
209 /// Returns a mutable iterator over the tree nodes, sorted by key.
210 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
214 // - `self.root` is a valid pointer to a tree root.
215 // - `bindings::rb_first` produces a valid pointer to a node given `root` is valid.
217 // SAFETY: by the invariants, all pointers are valid.
218 next: unsafe { bindings::rb_first(from_mut(&mut self.root)) },
219 _phantom: PhantomData,
224 /// Returns an iterator over the keys of the nodes in the tree, in sorted order.
225 pub fn keys(&self) -> impl Iterator<Item = &'_ K> {
226 self.iter().map(|(k, _)| k)
229 /// Returns an iterator over the values of the nodes in the tree, sorted by key.
230 pub fn values(&self) -> impl Iterator<Item = &'_ V> {
231 self.iter().map(|(_, v)| v)
234 /// Returns a mutable iterator over the values of the nodes in the tree, sorted by key.
235 pub fn values_mut(&mut self) -> impl Iterator<Item = &'_ mut V> {
236 self.iter_mut().map(|(_, v)| v)
239 /// Returns a cursor over the tree nodes, starting with the smallest key.
240 pub fn cursor_front(&mut self) -> Option<Cursor<'_, K, V>> {
241 let root = addr_of_mut!(self.root);
242 // SAFETY: `self.root` is always a valid root node
243 let current = unsafe { bindings::rb_first(root) };
244 NonNull::new(current).map(|current| {
246 // - `current` is a valid node in the [`RBTree`] pointed to by `self`.
254 /// Returns a cursor over the tree nodes, starting with the largest key.
255 pub fn cursor_back(&mut self) -> Option<Cursor<'_, K, V>> {
256 let root = addr_of_mut!(self.root);
257 // SAFETY: `self.root` is always a valid root node
258 let current = unsafe { bindings::rb_last(root) };
259 NonNull::new(current).map(|current| {
261 // - `current` is a valid node in the [`RBTree`] pointed to by `self`.
270 impl<K, V> RBTree<K, V>
274 /// Tries to insert a new value into the tree.
276 /// It overwrites a node if one already exists with the same key and returns it (containing the
277 /// key/value pair). Returns [`None`] if a node with the same key didn't already exist.
279 /// Returns an error if it cannot allocate memory for the new node.
280 pub fn try_create_and_insert(
285 ) -> Result<Option<RBTreeNode<K, V>>> {
286 Ok(self.insert(RBTreeNode::new(key, value, flags)?))
289 /// Inserts a new node into the tree.
291 /// It overwrites a node if one already exists with the same key and returns it (containing the
292 /// key/value pair). Returns [`None`] if a node with the same key didn't already exist.
294 /// This function always succeeds.
295 pub fn insert(&mut self, node: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
296 match self.raw_entry(&node.node.key) {
297 RawEntry::Occupied(entry) => Some(entry.replace(node)),
298 RawEntry::Vacant(entry) => {
305 fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> {
306 let raw_self: *mut RBTree<K, V> = self;
307 // The returned `RawEntry` is used to call either `rb_link_node` or `rb_replace_node`.
308 // The parameters of `bindings::rb_link_node` are as follows:
309 // - `node`: A pointer to an uninitialized node being inserted.
310 // - `parent`: A pointer to an existing node in the tree. One of its child pointers must be
311 // null, and `node` will become a child of `parent` by replacing that child pointer
312 // with a pointer to `node`.
313 // - `rb_link`: A pointer to either the left-child or right-child field of `parent`. This
314 // specifies which child of `parent` should hold `node` after this call. The
315 // value of `*rb_link` must be null before the call to `rb_link_node`. If the
316 // red/black tree is empty, then it’s also possible for `parent` to be null. In
317 // this case, `rb_link` is a pointer to the `root` field of the red/black tree.
319 // We will traverse the tree looking for a node that has a null pointer as its child,
320 // representing an empty subtree where we can insert our new node. We need to make sure
321 // that we preserve the ordering of the nodes in the tree. In each iteration of the loop
322 // we store `parent` and `child_field_of_parent`, and the new `node` will go somewhere
323 // in the subtree of `parent` that `child_field_of_parent` points at. Once
324 // we find an empty subtree, we can insert the new node using `rb_link_node`.
325 let mut parent = core::ptr::null_mut();
326 let mut child_field_of_parent: &mut *mut bindings::rb_node =
327 // SAFETY: `raw_self` is a valid pointer to the `RBTree` (created from `self` above).
328 unsafe { &mut (*raw_self).root.rb_node };
329 while !(*child_field_of_parent).is_null() {
330 let curr = *child_field_of_parent;
331 // SAFETY: All links fields we create are in a `Node<K, V>`.
332 let node = unsafe { container_of!(curr, Node<K, V>, links) };
334 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
335 match key.cmp(unsafe { &(*node).key }) {
336 // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
337 Ordering::Less => child_field_of_parent = unsafe { &mut (*curr).rb_left },
338 // SAFETY: `curr` is a non-null node so it is valid by the type invariants.
339 Ordering::Greater => child_field_of_parent = unsafe { &mut (*curr).rb_right },
341 return RawEntry::Occupied(OccupiedEntry {
350 RawEntry::Vacant(RawVacantEntry {
353 child_field_of_parent,
354 _phantom: PhantomData,
358 /// Gets the given key's corresponding entry in the map for in-place manipulation.
359 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
360 match self.raw_entry(&key) {
361 RawEntry::Occupied(entry) => Entry::Occupied(entry),
362 RawEntry::Vacant(entry) => Entry::Vacant(VacantEntry { raw: entry, key }),
366 /// Used for accessing the given node, if it exists.
367 pub fn find_mut(&mut self, key: &K) -> Option<OccupiedEntry<'_, K, V>> {
368 match self.raw_entry(key) {
369 RawEntry::Occupied(entry) => Some(entry),
370 RawEntry::Vacant(_entry) => None,
374 /// Returns a reference to the value corresponding to the key.
375 pub fn get(&self, key: &K) -> Option<&V> {
376 let mut node = self.root.rb_node;
377 while !node.is_null() {
378 // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
379 // point to the links field of `Node<K, V>` objects.
380 let this = unsafe { container_of!(node, Node<K, V>, links) };
381 // SAFETY: `this` is a non-null node so it is valid by the type invariants.
382 node = match key.cmp(unsafe { &(*this).key }) {
383 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
384 Ordering::Less => unsafe { (*node).rb_left },
385 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
386 Ordering::Greater => unsafe { (*node).rb_right },
387 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
388 Ordering::Equal => return Some(unsafe { &(*this).value }),
394 /// Returns a mutable reference to the value corresponding to the key.
395 pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
396 self.find_mut(key).map(|node| node.into_mut())
399 /// Removes the node with the given key from the tree.
401 /// It returns the node that was removed if one exists, or [`None`] otherwise.
402 pub fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
403 self.find_mut(key).map(OccupiedEntry::remove_node)
406 /// Removes the node with the given key from the tree.
408 /// It returns the value that was removed if one exists, or [`None`] otherwise.
409 pub fn remove(&mut self, key: &K) -> Option<V> {
410 self.find_mut(key).map(OccupiedEntry::remove)
413 /// Returns a cursor over the tree nodes based on the given key.
415 /// If the given key exists, the cursor starts there.
416 /// Otherwise it starts with the first larger key in sort order.
417 /// If there is no larger key, it returns [`None`].
418 pub fn cursor_lower_bound(&mut self, key: &K) -> Option<Cursor<'_, K, V>>
422 let mut node = self.root.rb_node;
423 let mut best_match: Option<NonNull<Node<K, V>>> = None;
424 while !node.is_null() {
425 // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
426 // point to the links field of `Node<K, V>` objects.
427 let this = unsafe { container_of!(node, Node<K, V>, links) }.cast_mut();
428 // SAFETY: `this` is a non-null node so it is valid by the type invariants.
429 let this_key = unsafe { &(*this).key };
430 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
431 let left_child = unsafe { (*node).rb_left };
432 // SAFETY: `node` is a non-null node so it is valid by the type invariants.
433 let right_child = unsafe { (*node).rb_right };
434 match key.cmp(this_key) {
436 best_match = NonNull::new(this);
439 Ordering::Greater => {
443 let is_better_match = match best_match {
446 // SAFETY: `best` is a non-null node so it is valid by the type invariants.
447 let best_key = unsafe { &(*best.as_ptr()).key };
452 best_match = NonNull::new(this);
459 let best = best_match?;
461 // SAFETY: `best` is a non-null node so it is valid by the type invariants.
462 let links = unsafe { addr_of_mut!((*best.as_ptr()).links) };
464 NonNull::new(links).map(|current| {
466 // - `current` is a valid node in the [`RBTree`] pointed to by `self`.
475 impl<K, V> Default for RBTree<K, V> {
476 fn default() -> Self {
481 impl<K, V> Drop for RBTree<K, V> {
483 // SAFETY: `root` is valid as it's embedded in `self` and we have a valid `self`.
484 let mut next = unsafe { bindings::rb_first_postorder(&self.root) };
486 // INVARIANT: The loop invariant is that all tree nodes from `next` in postorder are valid.
487 while !next.is_null() {
488 // SAFETY: All links fields we create are in a `Node<K, V>`.
489 let this = unsafe { container_of!(next, Node<K, V>, links) };
491 // Find out what the next node is before disposing of the current one.
492 // SAFETY: `next` and all nodes in postorder are still valid.
493 next = unsafe { bindings::rb_next_postorder(next) };
495 // INVARIANT: This is the destructor, so we break the type invariant during clean-up,
496 // but it is not observable. The loop invariant is still maintained.
498 // SAFETY: `this` is valid per the loop invariant.
499 unsafe { drop(KBox::from_raw(this.cast_mut())) };
504 /// A bidirectional cursor over the tree nodes, sorted by key.
508 /// In the following example, we obtain a cursor to the first element in the tree.
509 /// The cursor allows us to iterate bidirectionally over key/value pairs in the tree.
512 /// use kernel::{alloc::flags, rbtree::RBTree};
514 /// // Create a new tree.
515 /// let mut tree = RBTree::new();
517 /// // Insert three elements.
518 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
519 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
520 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
522 /// // Get a cursor to the first element.
523 /// let mut cursor = tree.cursor_front().unwrap();
524 /// let mut current = cursor.current();
525 /// assert_eq!(current, (&10, &100));
527 /// // Move the cursor, updating it to the 2nd element.
528 /// cursor = cursor.move_next().unwrap();
529 /// current = cursor.current();
530 /// assert_eq!(current, (&20, &200));
532 /// // Peek at the next element without impacting the cursor.
533 /// let next = cursor.peek_next().unwrap();
534 /// assert_eq!(next, (&30, &300));
535 /// current = cursor.current();
536 /// assert_eq!(current, (&20, &200));
538 /// // Moving past the last element causes the cursor to return [`None`].
539 /// cursor = cursor.move_next().unwrap();
540 /// current = cursor.current();
541 /// assert_eq!(current, (&30, &300));
542 /// let cursor = cursor.move_next();
543 /// assert!(cursor.is_none());
545 /// # Ok::<(), Error>(())
548 /// A cursor can also be obtained at the last element in the tree.
551 /// use kernel::{alloc::flags, rbtree::RBTree};
553 /// // Create a new tree.
554 /// let mut tree = RBTree::new();
556 /// // Insert three elements.
557 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
558 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
559 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
561 /// let mut cursor = tree.cursor_back().unwrap();
562 /// let current = cursor.current();
563 /// assert_eq!(current, (&30, &300));
565 /// # Ok::<(), Error>(())
568 /// Obtaining a cursor returns [`None`] if the tree is empty.
571 /// use kernel::rbtree::RBTree;
573 /// let mut tree: RBTree<u16, u16> = RBTree::new();
574 /// assert!(tree.cursor_front().is_none());
576 /// # Ok::<(), Error>(())
579 /// [`RBTree::cursor_lower_bound`] can be used to start at an arbitrary node in the tree.
582 /// use kernel::{alloc::flags, rbtree::RBTree};
584 /// // Create a new tree.
585 /// let mut tree = RBTree::new();
587 /// // Insert five elements.
588 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
589 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
590 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
591 /// tree.try_create_and_insert(40, 400, flags::GFP_KERNEL)?;
592 /// tree.try_create_and_insert(50, 500, flags::GFP_KERNEL)?;
594 /// // If the provided key exists, a cursor to that key is returned.
595 /// let cursor = tree.cursor_lower_bound(&20).unwrap();
596 /// let current = cursor.current();
597 /// assert_eq!(current, (&20, &200));
599 /// // If the provided key doesn't exist, a cursor to the first larger element in sort order is returned.
600 /// let cursor = tree.cursor_lower_bound(&25).unwrap();
601 /// let current = cursor.current();
602 /// assert_eq!(current, (&30, &300));
604 /// // If there is no larger key, [`None`] is returned.
605 /// let cursor = tree.cursor_lower_bound(&55);
606 /// assert!(cursor.is_none());
608 /// # Ok::<(), Error>(())
611 /// The cursor allows mutation of values in the tree.
614 /// use kernel::{alloc::flags, rbtree::RBTree};
616 /// // Create a new tree.
617 /// let mut tree = RBTree::new();
619 /// // Insert three elements.
620 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
621 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
622 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
624 /// // Retrieve a cursor.
625 /// let mut cursor = tree.cursor_front().unwrap();
627 /// // Get a mutable reference to the current value.
628 /// let (k, v) = cursor.current_mut();
631 /// // The updated value is reflected in the tree.
632 /// let updated = tree.get(&10).unwrap();
633 /// assert_eq!(updated, &1000);
635 /// # Ok::<(), Error>(())
638 /// It also allows node removal. The following examples demonstrate the behavior of removing the current node.
641 /// use kernel::{alloc::flags, rbtree::RBTree};
643 /// // Create a new tree.
644 /// let mut tree = RBTree::new();
646 /// // Insert three elements.
647 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
648 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
649 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
651 /// // Remove the first element.
652 /// let mut cursor = tree.cursor_front().unwrap();
653 /// let mut current = cursor.current();
654 /// assert_eq!(current, (&10, &100));
655 /// cursor = cursor.remove_current().0.unwrap();
657 /// // If a node exists after the current element, it is returned.
658 /// current = cursor.current();
659 /// assert_eq!(current, (&20, &200));
661 /// // Get a cursor to the last element, and remove it.
662 /// cursor = tree.cursor_back().unwrap();
663 /// current = cursor.current();
664 /// assert_eq!(current, (&30, &300));
666 /// // Since there is no next node, the previous node is returned.
667 /// cursor = cursor.remove_current().0.unwrap();
668 /// current = cursor.current();
669 /// assert_eq!(current, (&20, &200));
671 /// // Removing the last element in the tree returns [`None`].
672 /// assert!(cursor.remove_current().0.is_none());
674 /// # Ok::<(), Error>(())
677 /// Nodes adjacent to the current node can also be removed.
680 /// use kernel::{alloc::flags, rbtree::RBTree};
682 /// // Create a new tree.
683 /// let mut tree = RBTree::new();
685 /// // Insert three elements.
686 /// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?;
687 /// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?;
688 /// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?;
690 /// // Get a cursor to the first element.
691 /// let mut cursor = tree.cursor_front().unwrap();
692 /// let mut current = cursor.current();
693 /// assert_eq!(current, (&10, &100));
695 /// // Calling `remove_prev` from the first element returns [`None`].
696 /// assert!(cursor.remove_prev().is_none());
698 /// // Get a cursor to the last element.
699 /// cursor = tree.cursor_back().unwrap();
700 /// current = cursor.current();
701 /// assert_eq!(current, (&30, &300));
703 /// // Calling `remove_prev` removes and returns the middle element.
704 /// assert_eq!(cursor.remove_prev().unwrap().to_key_value(), (20, 200));
706 /// // Calling `remove_next` from the last element returns [`None`].
707 /// assert!(cursor.remove_next().is_none());
709 /// // Move to the first element
710 /// cursor = cursor.move_prev().unwrap();
711 /// current = cursor.current();
712 /// assert_eq!(current, (&10, &100));
714 /// // Calling `remove_next` removes and returns the last element.
715 /// assert_eq!(cursor.remove_next().unwrap().to_key_value(), (30, 300));
717 /// # Ok::<(), Error>(())
722 /// - `current` points to a node that is in the same [`RBTree`] as `tree`.
723 pub struct Cursor<'a, K, V> {
724 tree: &'a mut RBTree<K, V>,
725 current: NonNull<bindings::rb_node>,
728 // SAFETY: The [`Cursor`] has exclusive access to both `K` and `V`, so it is sufficient to require them to be `Send`.
729 // The cursor only gives out immutable references to the keys, but since it has excusive access to those same
730 // keys, `Send` is sufficient. `Sync` would be okay, but it is more restrictive to the user.
731 unsafe impl<'a, K: Send, V: Send> Send for Cursor<'a, K, V> {}
733 // SAFETY: The [`Cursor`] gives out immutable references to K and mutable references to V,
734 // so it has the same thread safety requirements as mutable references.
735 unsafe impl<'a, K: Sync, V: Sync> Sync for Cursor<'a, K, V> {}
737 impl<'a, K, V> Cursor<'a, K, V> {
739 pub fn current(&self) -> (&K, &V) {
741 // - `self.current` is a valid node by the type invariants.
742 // - We have an immutable reference by the function signature.
743 unsafe { Self::to_key_value(self.current) }
746 /// The current node, with a mutable value
747 pub fn current_mut(&mut self) -> (&K, &mut V) {
749 // - `self.current` is a valid node by the type invariants.
750 // - We have an mutable reference by the function signature.
751 unsafe { Self::to_key_value_mut(self.current) }
754 /// Remove the current node from the tree.
756 /// Returns a tuple where the first element is a cursor to the next node, if it exists,
757 /// else the previous node, else [`None`] (if the tree becomes empty). The second element
758 /// is the removed node.
759 pub fn remove_current(self) -> (Option<Self>, RBTreeNode<K, V>) {
760 let prev = self.get_neighbor_raw(Direction::Prev);
761 let next = self.get_neighbor_raw(Direction::Next);
762 // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
763 // point to the links field of `Node<K, V>` objects.
764 let this = unsafe { container_of!(self.current.as_ptr(), Node<K, V>, links) }.cast_mut();
765 // SAFETY: `this` is valid by the type invariants as described above.
766 let node = unsafe { KBox::from_raw(this) };
767 let node = RBTreeNode { node };
768 // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
769 // the tree cannot change. By the tree invariant, all nodes are valid.
770 unsafe { bindings::rb_erase(&mut (*this).links, addr_of_mut!(self.tree.root)) };
772 let current = match (prev, next) {
773 (_, Some(next)) => next,
774 (Some(prev), None) => prev,
782 // - `current` is a valid node in the [`RBTree`] pointed to by `self.tree`.
791 /// Remove the previous node, returning it if it exists.
792 pub fn remove_prev(&mut self) -> Option<RBTreeNode<K, V>> {
793 self.remove_neighbor(Direction::Prev)
796 /// Remove the next node, returning it if it exists.
797 pub fn remove_next(&mut self) -> Option<RBTreeNode<K, V>> {
798 self.remove_neighbor(Direction::Next)
801 fn remove_neighbor(&mut self, direction: Direction) -> Option<RBTreeNode<K, V>> {
802 if let Some(neighbor) = self.get_neighbor_raw(direction) {
803 let neighbor = neighbor.as_ptr();
804 // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so
805 // the tree cannot change. By the tree invariant, all nodes are valid.
806 unsafe { bindings::rb_erase(neighbor, addr_of_mut!(self.tree.root)) };
807 // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
808 // point to the links field of `Node<K, V>` objects.
809 let this = unsafe { container_of!(neighbor, Node<K, V>, links) }.cast_mut();
810 // SAFETY: `this` is valid by the type invariants as described above.
811 let node = unsafe { KBox::from_raw(this) };
812 return Some(RBTreeNode { node });
817 /// Move the cursor to the previous node, returning [`None`] if it doesn't exist.
818 pub fn move_prev(self) -> Option<Self> {
819 self.mv(Direction::Prev)
822 /// Move the cursor to the next node, returning [`None`] if it doesn't exist.
823 pub fn move_next(self) -> Option<Self> {
824 self.mv(Direction::Next)
827 fn mv(self, direction: Direction) -> Option<Self> {
829 // - `neighbor` is a valid node in the [`RBTree`] pointed to by `self.tree`.
830 self.get_neighbor_raw(direction).map(|neighbor| Self {
836 /// Access the previous node without moving the cursor.
837 pub fn peek_prev(&self) -> Option<(&K, &V)> {
838 self.peek(Direction::Prev)
841 /// Access the previous node without moving the cursor.
842 pub fn peek_next(&self) -> Option<(&K, &V)> {
843 self.peek(Direction::Next)
846 fn peek(&self, direction: Direction) -> Option<(&K, &V)> {
847 self.get_neighbor_raw(direction).map(|neighbor| {
849 // - `neighbor` is a valid tree node.
850 // - By the function signature, we have an immutable reference to `self`.
851 unsafe { Self::to_key_value(neighbor) }
855 /// Access the previous node mutably without moving the cursor.
856 pub fn peek_prev_mut(&mut self) -> Option<(&K, &mut V)> {
857 self.peek_mut(Direction::Prev)
860 /// Access the next node mutably without moving the cursor.
861 pub fn peek_next_mut(&mut self) -> Option<(&K, &mut V)> {
862 self.peek_mut(Direction::Next)
865 fn peek_mut(&mut self, direction: Direction) -> Option<(&K, &mut V)> {
866 self.get_neighbor_raw(direction).map(|neighbor| {
868 // - `neighbor` is a valid tree node.
869 // - By the function signature, we have a mutable reference to `self`.
870 unsafe { Self::to_key_value_mut(neighbor) }
874 fn get_neighbor_raw(&self, direction: Direction) -> Option<NonNull<bindings::rb_node>> {
875 // SAFETY: `self.current` is valid by the type invariants.
876 let neighbor = unsafe {
878 Direction::Prev => bindings::rb_prev(self.current.as_ptr()),
879 Direction::Next => bindings::rb_next(self.current.as_ptr()),
883 NonNull::new(neighbor)
888 /// - `node` must be a valid pointer to a node in an [`RBTree`].
889 /// - The caller has immutable access to `node` for the duration of 'b.
890 unsafe fn to_key_value<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b V) {
891 // SAFETY: the caller guarantees that `node` is a valid pointer in an `RBTree`.
892 let (k, v) = unsafe { Self::to_key_value_raw(node) };
893 // SAFETY: the caller guarantees immutable access to `node`.
899 /// - `node` must be a valid pointer to a node in an [`RBTree`].
900 /// - The caller has mutable access to `node` for the duration of 'b.
901 unsafe fn to_key_value_mut<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b mut V) {
902 // SAFETY: the caller guarantees that `node` is a valid pointer in an `RBTree`.
903 let (k, v) = unsafe { Self::to_key_value_raw(node) };
904 // SAFETY: the caller guarantees mutable access to `node`.
905 (k, unsafe { &mut *v })
910 /// - `node` must be a valid pointer to a node in an [`RBTree`].
911 /// - The caller has immutable access to the key for the duration of 'b.
912 unsafe fn to_key_value_raw<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, *mut V) {
913 // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
914 // point to the links field of `Node<K, V>` objects.
915 let this = unsafe { container_of!(node.as_ptr(), Node<K, V>, links) }.cast_mut();
916 // SAFETY: The passed `node` is the current node or a non-null neighbor,
917 // thus `this` is valid by the type invariants.
918 let k = unsafe { &(*this).key };
919 // SAFETY: The passed `node` is the current node or a non-null neighbor,
920 // thus `this` is valid by the type invariants.
921 let v = unsafe { addr_of_mut!((*this).value) };
926 /// Direction for [`Cursor`] operations.
928 /// the node immediately before, in sort order
930 /// the node immediately after, in sort order
934 impl<'a, K, V> IntoIterator for &'a RBTree<K, V> {
935 type Item = (&'a K, &'a V);
936 type IntoIter = Iter<'a, K, V>;
938 fn into_iter(self) -> Self::IntoIter {
943 /// An iterator over the nodes of a [`RBTree`].
945 /// Instances are created by calling [`RBTree::iter`].
946 pub struct Iter<'a, K, V> {
947 _tree: PhantomData<&'a RBTree<K, V>>,
948 iter_raw: IterRaw<K, V>,
951 // SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same
952 // thread safety requirements as immutable references.
953 unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {}
955 // SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same
956 // thread safety requirements as immutable references.
957 unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {}
959 impl<'a, K, V> Iterator for Iter<'a, K, V> {
960 type Item = (&'a K, &'a V);
962 fn next(&mut self) -> Option<Self::Item> {
963 // SAFETY: Due to `self._tree`, `k` and `v` are valid for the lifetime of `'a`.
964 self.iter_raw.next().map(|(k, v)| unsafe { (&*k, &*v) })
968 impl<'a, K, V> IntoIterator for &'a mut RBTree<K, V> {
969 type Item = (&'a K, &'a mut V);
970 type IntoIter = IterMut<'a, K, V>;
972 fn into_iter(self) -> Self::IntoIter {
977 /// A mutable iterator over the nodes of a [`RBTree`].
979 /// Instances are created by calling [`RBTree::iter_mut`].
980 pub struct IterMut<'a, K, V> {
981 _tree: PhantomData<&'a mut RBTree<K, V>>,
982 iter_raw: IterRaw<K, V>,
985 // SAFETY: The [`IterMut`] has exclusive access to both `K` and `V`, so it is sufficient to require them to be `Send`.
986 // The iterator only gives out immutable references to the keys, but since the iterator has excusive access to those same
987 // keys, `Send` is sufficient. `Sync` would be okay, but it is more restrictive to the user.
988 unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {}
990 // SAFETY: The [`IterMut`] gives out immutable references to K and mutable references to V, so it has the same
991 // thread safety requirements as mutable references.
992 unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {}
994 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
995 type Item = (&'a K, &'a mut V);
997 fn next(&mut self) -> Option<Self::Item> {
998 self.iter_raw.next().map(|(k, v)|
999 // SAFETY: Due to `&mut self`, we have exclusive access to `k` and `v`, for the lifetime of `'a`.
1000 unsafe { (&*k, &mut *v) })
1004 /// A raw iterator over the nodes of a [`RBTree`].
1007 /// - `self.next` is a valid pointer.
1008 /// - `self.next` points to a node stored inside of a valid `RBTree`.
1009 struct IterRaw<K, V> {
1010 next: *mut bindings::rb_node,
1011 _phantom: PhantomData<fn() -> (K, V)>,
1014 impl<K, V> Iterator for IterRaw<K, V> {
1015 type Item = (*mut K, *mut V);
1017 fn next(&mut self) -> Option<Self::Item> {
1018 if self.next.is_null() {
1022 // SAFETY: By the type invariant of `IterRaw`, `self.next` is a valid node in an `RBTree`,
1023 // and by the type invariant of `RBTree`, all nodes point to the links field of `Node<K, V>` objects.
1024 let cur = unsafe { container_of!(self.next, Node<K, V>, links) }.cast_mut();
1026 // SAFETY: `self.next` is a valid tree node by the type invariants.
1027 self.next = unsafe { bindings::rb_next(self.next) };
1029 // SAFETY: By the same reasoning above, it is safe to dereference the node.
1030 Some(unsafe { (addr_of_mut!((*cur).key), addr_of_mut!((*cur).value)) })
1034 /// A memory reservation for a red-black tree node.
1037 /// It contains the memory needed to hold a node that can be inserted into a red-black tree. One
1038 /// can be obtained by directly allocating it ([`RBTreeNodeReservation::new`]).
1039 pub struct RBTreeNodeReservation<K, V> {
1040 node: KBox<MaybeUninit<Node<K, V>>>,
1043 impl<K, V> RBTreeNodeReservation<K, V> {
1044 /// Allocates memory for a node to be eventually initialised and inserted into the tree via a
1045 /// call to [`RBTree::insert`].
1046 pub fn new(flags: Flags) -> Result<RBTreeNodeReservation<K, V>> {
1047 Ok(RBTreeNodeReservation {
1048 node: KBox::new_uninit(flags)?,
1053 // SAFETY: This doesn't actually contain K or V, and is just a memory allocation. Those can always
1054 // be moved across threads.
1055 unsafe impl<K, V> Send for RBTreeNodeReservation<K, V> {}
1057 // SAFETY: This doesn't actually contain K or V, and is just a memory allocation.
1058 unsafe impl<K, V> Sync for RBTreeNodeReservation<K, V> {}
1060 impl<K, V> RBTreeNodeReservation<K, V> {
1061 /// Initialises a node reservation.
1063 /// It then becomes an [`RBTreeNode`] that can be inserted into a tree.
1064 pub fn into_node(self, key: K, value: V) -> RBTreeNode<K, V> {
1065 let node = KBox::write(
1070 links: bindings::rb_node::default(),
1077 /// A red-black tree node.
1079 /// The node is fully initialised (with key and value) and can be inserted into a tree without any
1080 /// extra allocations or failure paths.
1081 pub struct RBTreeNode<K, V> {
1082 node: KBox<Node<K, V>>,
1085 impl<K, V> RBTreeNode<K, V> {
1086 /// Allocates and initialises a node that can be inserted into the tree via
1087 /// [`RBTree::insert`].
1088 pub fn new(key: K, value: V, flags: Flags) -> Result<RBTreeNode<K, V>> {
1089 Ok(RBTreeNodeReservation::new(flags)?.into_node(key, value))
1092 /// Get the key and value from inside the node.
1093 pub fn to_key_value(self) -> (K, V) {
1094 let node = KBox::into_inner(self.node);
1096 (node.key, node.value)
1100 // SAFETY: If K and V can be sent across threads, then it's also okay to send [`RBTreeNode`] across
1102 unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
1104 // SAFETY: If K and V can be accessed without synchronization, then it's also okay to access
1105 // [`RBTreeNode`] without synchronization.
1106 unsafe impl<K: Sync, V: Sync> Sync for RBTreeNode<K, V> {}
1108 impl<K, V> RBTreeNode<K, V> {
1109 /// Drop the key and value, but keep the allocation.
1111 /// It then becomes a reservation that can be re-initialised into a different node (i.e., with
1112 /// a different key and/or value).
1114 /// The existing key and value are dropped in-place as part of this operation, that is, memory
1115 /// may be freed (but only for the key/value; memory for the node itself is kept for reuse).
1116 pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
1117 RBTreeNodeReservation {
1118 node: KBox::drop_contents(self.node),
1123 /// A view into a single entry in a map, which may either be vacant or occupied.
1125 /// This enum is constructed from the [`RBTree::entry`].
1127 /// [`entry`]: fn@RBTree::entry
1128 pub enum Entry<'a, K, V> {
1129 /// This [`RBTree`] does not have a node with this key.
1130 Vacant(VacantEntry<'a, K, V>),
1131 /// This [`RBTree`] already has a node with this key.
1132 Occupied(OccupiedEntry<'a, K, V>),
1135 /// Like [`Entry`], except that it doesn't have ownership of the key.
1136 enum RawEntry<'a, K, V> {
1137 Vacant(RawVacantEntry<'a, K, V>),
1138 Occupied(OccupiedEntry<'a, K, V>),
1141 /// A view into a vacant entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1142 pub struct VacantEntry<'a, K, V> {
1144 raw: RawVacantEntry<'a, K, V>,
1147 /// Like [`VacantEntry`], but doesn't hold on to the key.
1150 /// - `parent` may be null if the new node becomes the root.
1151 /// - `child_field_of_parent` is a valid pointer to the left-child or right-child of `parent`. If `parent` is
1152 /// null, it is a pointer to the root of the [`RBTree`].
1153 struct RawVacantEntry<'a, K, V> {
1154 rbtree: *mut RBTree<K, V>,
1155 /// The node that will become the parent of the new node if we insert one.
1156 parent: *mut bindings::rb_node,
1157 /// This points to the left-child or right-child field of `parent`, or `root` if `parent` is
1159 child_field_of_parent: *mut *mut bindings::rb_node,
1160 _phantom: PhantomData<&'a mut RBTree<K, V>>,
1163 impl<'a, K, V> RawVacantEntry<'a, K, V> {
1164 /// Inserts the given node into the [`RBTree`] at this entry.
1166 /// The `node` must have a key such that inserting it here does not break the ordering of this
1168 fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
1169 let node = KBox::into_raw(node.node);
1171 // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1172 // the node is removed or replaced.
1173 let node_links = unsafe { addr_of_mut!((*node).links) };
1175 // INVARIANT: We are linking in a new node, which is valid. It remains valid because we
1176 // "forgot" it with `Box::into_raw`.
1177 // SAFETY: The type invariants of `RawVacantEntry` are exactly the safety requirements of `rb_link_node`.
1178 unsafe { bindings::rb_link_node(node_links, self.parent, self.child_field_of_parent) };
1180 // SAFETY: All pointers are valid. `node` has just been inserted into the tree.
1181 unsafe { bindings::rb_insert_color(node_links, addr_of_mut!((*self.rbtree).root)) };
1183 // SAFETY: The node is valid until we remove it from the tree.
1184 unsafe { &mut (*node).value }
1188 impl<'a, K, V> VacantEntry<'a, K, V> {
1189 /// Inserts the given node into the [`RBTree`] at this entry.
1190 pub fn insert(self, value: V, reservation: RBTreeNodeReservation<K, V>) -> &'a mut V {
1191 self.raw.insert(reservation.into_node(self.key, value))
1195 /// A view into an occupied entry in a [`RBTree`]. It is part of the [`Entry`] enum.
1198 /// - `node_links` is a valid, non-null pointer to a tree node in `self.rbtree`
1199 pub struct OccupiedEntry<'a, K, V> {
1200 rbtree: &'a mut RBTree<K, V>,
1201 /// The node that this entry corresponds to.
1202 node_links: *mut bindings::rb_node,
1205 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1206 /// Gets a reference to the value in the entry.
1207 pub fn get(&self) -> &V {
1209 // - `self.node_links` is a valid pointer to a node in the tree.
1210 // - We have shared access to the underlying tree, and can thus give out a shared reference.
1211 unsafe { &(*container_of!(self.node_links, Node<K, V>, links)).value }
1214 /// Gets a mutable reference to the value in the entry.
1215 pub fn get_mut(&mut self) -> &mut V {
1217 // - `self.node_links` is a valid pointer to a node in the tree.
1218 // - We have exclusive access to the underlying tree, and can thus give out a mutable reference.
1219 unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links).cast_mut())).value }
1222 /// Converts the entry into a mutable reference to its value.
1224 /// If you need multiple references to the `OccupiedEntry`, see [`self#get_mut`].
1225 pub fn into_mut(self) -> &'a mut V {
1227 // - `self.node_links` is a valid pointer to a node in the tree.
1228 // - This consumes the `&'a mut RBTree<K, V>`, therefore it can give out a mutable reference that lives for `'a`.
1229 unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links).cast_mut())).value }
1232 /// Remove this entry from the [`RBTree`].
1233 pub fn remove_node(self) -> RBTreeNode<K, V> {
1234 // SAFETY: The node is a node in the tree, so it is valid.
1235 unsafe { bindings::rb_erase(self.node_links, &mut self.rbtree.root) };
1237 // INVARIANT: The node is being returned and the caller may free it, however, it was
1238 // removed from the tree. So the invariants still hold.
1240 // SAFETY: The node was a node in the tree, but we removed it, so we can convert it
1243 KBox::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut())
1248 /// Takes the value of the entry out of the map, and returns it.
1249 pub fn remove(self) -> V {
1250 let rb_node = self.remove_node();
1251 let node = KBox::into_inner(rb_node.node);
1256 /// Swap the current node for the provided node.
1258 /// The key of both nodes must be equal.
1259 fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
1260 let node = KBox::into_raw(node.node);
1262 // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when
1263 // the node is removed or replaced.
1264 let new_node_links = unsafe { addr_of_mut!((*node).links) };
1266 // SAFETY: This updates the pointers so that `new_node_links` is in the tree where
1267 // `self.node_links` used to be.
1269 bindings::rb_replace_node(self.node_links, new_node_links, &mut self.rbtree.root)
1273 // - `self.node_ptr` produces a valid pointer to a node in the tree.
1274 // - Now that we removed this entry from the tree, we can convert the node to a box.
1276 unsafe { KBox::from_raw(container_of!(self.node_links, Node<K, V>, links).cast_mut()) };
1278 RBTreeNode { node: old_node }
1283 links: bindings::rb_node,