Skip to content

Commit 0767c03

Browse files
wedsonafmatthewtgilbride
authored andcommitted
rust: rbtree: add iterator
- Add Iterator implementation for `RBTree`, allowing iteration over (key, value) pairs in key order. - Add individual `keys()` and `values()` functions to iterate over keys or values alone. - Update doctests to use iteration instead of explicitly getting items. Iteration is needed by the binder driver to enumerate all values in a tree for oneway spam detection [1]. Link: https://lore.kernel.org/rust-for-linux/[email protected]/ [1] Signed-off-by: Wedson Almeida Filho <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Tested-by: Alice Ryhl <[email protected]> Signed-off-by: Matt Gilbride <[email protected]>
1 parent 1c75925 commit 0767c03

File tree

1 file changed

+112
-18
lines changed

1 file changed

+112
-18
lines changed

rust/kernel/rbtree.rs

Lines changed: 112 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -47,34 +47,53 @@ use core::{
4747
/// assert_eq!(tree.get(&30).unwrap(), &300);
4848
/// }
4949
///
50+
/// // Iterate over the nodes we just inserted.
51+
/// {
52+
/// let mut iter = tree.iter();
53+
/// assert_eq!(iter.next().unwrap(), (&10, &100));
54+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
55+
/// assert_eq!(iter.next().unwrap(), (&30, &300));
56+
/// assert!(iter.next().is_none());
57+
/// }
58+
///
59+
/// // Print all elements.
60+
/// for (key, value) in &tree {
61+
/// pr_info!("{} = {}\n", key, value);
62+
/// }
63+
///
5064
/// // Replace one of the elements.
5165
/// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?;
5266
///
5367
/// // Check that the tree reflects the replacement.
5468
/// {
55-
/// assert_eq!(tree.get(&10).unwrap(), &1000);
56-
/// assert_eq!(tree.get(&20).unwrap(), &200);
57-
/// assert_eq!(tree.get(&30).unwrap(), &300);
69+
/// let mut iter = tree.iter();
70+
/// assert_eq!(iter.next().unwrap(), (&10, &1000));
71+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
72+
/// assert_eq!(iter.next().unwrap(), (&30, &300));
73+
/// assert!(iter.next().is_none());
5874
/// }
5975
///
6076
/// // Change the value of one of the elements.
6177
/// *tree.get_mut(&30).unwrap() = 3000;
6278
///
6379
/// // Check that the tree reflects the update.
6480
/// {
65-
/// assert_eq!(tree.get(&10).unwrap(), &1000);
66-
/// assert_eq!(tree.get(&20).unwrap(), &200);
67-
/// assert_eq!(tree.get(&30).unwrap(), &3000);
81+
/// let mut iter = tree.iter();
82+
/// assert_eq!(iter.next().unwrap(), (&10, &1000));
83+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
84+
/// assert_eq!(iter.next().unwrap(), (&30, &3000));
85+
/// assert!(iter.next().is_none());
6886
/// }
6987
///
7088
/// // Remove an element.
7189
/// tree.remove(&10);
7290
///
7391
/// // Check that the tree reflects the removal.
7492
/// {
75-
/// assert_eq!(tree.get(&10), None);
76-
/// assert_eq!(tree.get(&20).unwrap(), &200);
77-
/// assert_eq!(tree.get(&30).unwrap(), &3000);
93+
/// let mut iter = tree.iter();
94+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
95+
/// assert_eq!(iter.next().unwrap(), (&30, &3000));
96+
/// assert!(iter.next().is_none());
7897
/// }
7998
///
8099
/// # Ok::<(), Error>(())
@@ -114,19 +133,22 @@ use core::{
114133
///
115134
/// // Check the nodes we just inserted.
116135
/// {
117-
/// assert_eq!(tree.get(&10).unwrap(), &100);
118-
/// assert_eq!(tree.get(&20).unwrap(), &200);
119-
/// assert_eq!(tree.get(&30).unwrap(), &300);
136+
/// let mut iter = tree.iter();
137+
/// assert_eq!(iter.next().unwrap(), (&10, &100));
138+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
139+
/// assert_eq!(iter.next().unwrap(), (&30, &300));
140+
/// assert!(iter.next().is_none());
120141
/// }
121142
///
122143
/// // Remove a node, getting back ownership of it.
123144
/// let existing = tree.remove(&30).unwrap();
124145
///
125146
/// // Check that the tree reflects the removal.
126147
/// {
127-
/// assert_eq!(tree.get(&10).unwrap(), &100);
128-
/// assert_eq!(tree.get(&20).unwrap(), &200);
129-
/// assert_eq!(tree.get(&30), None);
148+
/// let mut iter = tree.iter();
149+
/// assert_eq!(iter.next().unwrap(), (&10, &100));
150+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
151+
/// assert!(iter.next().is_none());
130152
/// }
131153
///
132154
/// // Create a preallocated reservation that we can re-use later.
@@ -138,9 +160,11 @@ use core::{
138160
///
139161
/// // Check that the tree reflect the new insertion.
140162
/// {
141-
/// assert_eq!(tree.get(&10).unwrap(), &100);
142-
/// assert_eq!(tree.get(&15).unwrap(), &150);
143-
/// assert_eq!(tree.get(&20).unwrap(), &200);
163+
/// let mut iter = tree.iter();
164+
/// assert_eq!(iter.next().unwrap(), (&10, &100));
165+
/// assert_eq!(iter.next().unwrap(), (&15, &150));
166+
/// assert_eq!(iter.next().unwrap(), (&20, &200));
167+
/// assert!(iter.next().is_none());
144168
/// }
145169
///
146170
/// # Ok::<(), Error>(())
@@ -167,6 +191,26 @@ impl<K, V> RBTree<K, V> {
167191
_p: PhantomData,
168192
}
169193
}
194+
195+
/// Returns an iterator over the tree nodes, sorted by key.
196+
pub fn iter(&self) -> Iter<'_, K, V> {
197+
// INVARIANT: `bindings::rb_first` returns a valid pointer to a tree node given a valid pointer to a tree root.
198+
Iter {
199+
_tree: PhantomData,
200+
// SAFETY: `self.root` is a valid pointer to the tree root.
201+
next: unsafe { bindings::rb_first(&self.root) },
202+
}
203+
}
204+
205+
/// Returns an iterator over the keys of the nodes in the tree, in sorted order.
206+
pub fn keys(&self) -> impl Iterator<Item = &'_ K> {
207+
self.iter().map(|(k, _)| k)
208+
}
209+
210+
/// Returns an iterator over the values of the nodes in the tree, sorted by key.
211+
pub fn values(&self) -> impl Iterator<Item = &'_ V> {
212+
self.iter().map(|(_, v)| v)
213+
}
170214
}
171215

172216
impl<K, V> RBTree<K, V>
@@ -358,6 +402,56 @@ impl<K, V> Drop for RBTree<K, V> {
358402
}
359403
}
360404

405+
impl<'a, K, V> IntoIterator for &'a RBTree<K, V> {
406+
type Item = (&'a K, &'a V);
407+
type IntoIter = Iter<'a, K, V>;
408+
409+
fn into_iter(self) -> Self::IntoIter {
410+
self.iter()
411+
}
412+
}
413+
414+
/// An iterator over the nodes of a [`RBTree`].
415+
///
416+
/// Instances are created by calling [`RBTree::iter`].
417+
///
418+
/// # Invariants
419+
/// - `self.next` is a valid pointer.
420+
/// - `self.next` points to a node stored inside of a valid `RBTree`.
421+
pub struct Iter<'a, K, V> {
422+
_tree: PhantomData<&'a RBTree<K, V>>,
423+
next: *mut bindings::rb_node,
424+
}
425+
426+
// SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same
427+
// thread safety requirements as immutable references.
428+
unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {}
429+
430+
// SAFETY: The [`Iter`] gives out immutable references to K and V, so it has the same
431+
// thread safety requirements as immutable references.
432+
unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {}
433+
434+
impl<'a, K, V> Iterator for Iter<'a, K, V> {
435+
type Item = (&'a K, &'a V);
436+
437+
fn next(&mut self) -> Option<Self::Item> {
438+
if self.next.is_null() {
439+
return None;
440+
}
441+
442+
// SAFETY: By the type invariant of `Iter`, `self.next` is a valid node in an `RBTree`,
443+
// and by the type invariant of `RBTree`, all nodes point to the links field of `Node<K, V>` objects.
444+
let cur = unsafe { container_of!(self.next, Node<K, V>, links) };
445+
446+
// SAFETY: `self.next` is a valid tree node by the type invariants.
447+
self.next = unsafe { bindings::rb_next(self.next) };
448+
449+
// SAFETY: By the same reasoning above, it is safe to dereference the node. Additionally,
450+
// it is ok to return a reference to members because the iterator must outlive it.
451+
Some(unsafe { (&(*cur).key, &(*cur).value) })
452+
}
453+
}
454+
361455
/// A memory reservation for a red-black tree node.
362456
///
363457
///

0 commit comments

Comments
 (0)