[PATCH v2 2/3] rust: kernel: implement iterators for ScatterList

From: Qingsong Chen
Date: Fri Jun 02 2023 - 06:18:58 EST


ScatterList could be transmuted from raw pointers of a valid
`sg_table`. Then we can use those iterators to access the
following normal entries.

Signed-off-by: Qingsong Chen <changxian.cqs@xxxxxxxxxxxx>
---
rust/kernel/scatterlist.rs | 50 ++++++++++++++++++++++++++++++++++++++
1 file changed, 50 insertions(+)

diff --git a/rust/kernel/scatterlist.rs b/rust/kernel/scatterlist.rs
index 8d6a34afb191..292fcb63a329 100644
--- a/rust/kernel/scatterlist.rs
+++ b/rust/kernel/scatterlist.rs
@@ -277,4 +277,54 @@ impl ScatterList<'_> {
// SAFETY: By the type invariant, we know that `self.opaque` is valid.
unsafe { bindings::sg_nents(self.opaque.get()) as _ }
}
+
+ /// Get an iterator for immutable references.
+ pub fn iter(&self) -> Iter<'_> {
+ Iter(ScatterList::as_ref(self.opaque.get()))
+ }
+
+ /// Get an iterator for mutable references.
+ pub fn iter_mut(&mut self) -> IterMut<'_> {
+ IterMut(ScatterList::as_mut(self.opaque.get()))
+ }
+}
+
+/// An iterator that yields [`Pin<&ScatterList>`].
+///
+/// Only iterate normal scatterlist entries, chainable entry will be skipped.
+pub struct Iter<'a>(Option<Pin<&'a ScatterList<'a>>>);
+
+impl<'a> Iterator for Iter<'a> {
+ type Item = Pin<&'a ScatterList<'a>>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.0.is_none() {
+ return None;
+ }
+ let ptr = self.0.as_ref().unwrap().opaque.get();
+ // SAFETY: `ptr` is from `self.opaque`, it is valid by the type invariant.
+ let next = unsafe { bindings::sg_next(ptr) };
+ self.0 = ScatterList::as_ref(next);
+ ScatterList::as_ref(ptr)
+ }
+}
+
+/// An iterator that yields [`Pin<&mut ScatterList>`].
+///
+/// Only iterate normal scatterlist entries, chainable entry will be skipped.
+pub struct IterMut<'a>(Option<Pin<&'a mut ScatterList<'a>>>);
+
+impl<'a> Iterator for IterMut<'a> {
+ type Item = Pin<&'a mut ScatterList<'a>>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.0.is_none() {
+ return None;
+ }
+ let ptr = self.0.as_ref().unwrap().opaque.get();
+ // SAFETY: `ptr` is from `self.opaque`, it is valid by the type invariant.
+ let next = unsafe { bindings::sg_next(ptr) };
+ self.0 = ScatterList::as_mut(next);
+ ScatterList::as_mut(ptr)
+ }
}
--
2.40.1