@@ -47,34 +47,53 @@ use core::{
47
47
/// assert_eq!(tree.get(&30).unwrap(), &300);
48
48
/// }
49
49
///
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
+ ///
50
64
/// // Replace one of the elements.
51
65
/// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?;
52
66
///
53
67
/// // Check that the tree reflects the replacement.
54
68
/// {
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());
58
74
/// }
59
75
///
60
76
/// // Change the value of one of the elements.
61
77
/// *tree.get_mut(&30).unwrap() = 3000;
62
78
///
63
79
/// // Check that the tree reflects the update.
64
80
/// {
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());
68
86
/// }
69
87
///
70
88
/// // Remove an element.
71
89
/// tree.remove(&10);
72
90
///
73
91
/// // Check that the tree reflects the removal.
74
92
/// {
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());
78
97
/// }
79
98
///
80
99
/// # Ok::<(), Error>(())
@@ -114,19 +133,22 @@ use core::{
114
133
///
115
134
/// // Check the nodes we just inserted.
116
135
/// {
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());
120
141
/// }
121
142
///
122
143
/// // Remove a node, getting back ownership of it.
123
144
/// let existing = tree.remove(&30).unwrap();
124
145
///
125
146
/// // Check that the tree reflects the removal.
126
147
/// {
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());
130
152
/// }
131
153
///
132
154
/// // Create a preallocated reservation that we can re-use later.
@@ -138,9 +160,11 @@ use core::{
138
160
///
139
161
/// // Check that the tree reflect the new insertion.
140
162
/// {
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());
144
168
/// }
145
169
///
146
170
/// # Ok::<(), Error>(())
@@ -167,6 +191,26 @@ impl<K, V> RBTree<K, V> {
167
191
_p : PhantomData ,
168
192
}
169
193
}
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
+ }
170
214
}
171
215
172
216
impl < K , V > RBTree < K , V >
@@ -358,6 +402,56 @@ impl<K, V> Drop for RBTree<K, V> {
358
402
}
359
403
}
360
404
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
+
361
455
/// A memory reservation for a red-black tree node.
362
456
///
363
457
///
0 commit comments