summaryrefslogtreecommitdiff
path: root/kernel/src/collections/stack_linked_list.rs
diff options
context:
space:
mode:
Diffstat (limited to 'kernel/src/collections/stack_linked_list.rs')
-rw-r--r--kernel/src/collections/stack_linked_list.rs36
1 files changed, 35 insertions, 1 deletions
diff --git a/kernel/src/collections/stack_linked_list.rs b/kernel/src/collections/stack_linked_list.rs
index ce9ee8e..19b9272 100644
--- a/kernel/src/collections/stack_linked_list.rs
+++ b/kernel/src/collections/stack_linked_list.rs
@@ -4,7 +4,7 @@ use core::fmt;
/// A linked list whose nodes can be stack-allocated.
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
-pub struct StackLinkedList<'list, T>(pub Option<(T, &'list StackLinkedList<'list, T>)>);
+pub struct StackLinkedList<'list, T>(Option<(T, &'list StackLinkedList<'list, T>)>);
impl<'list, T> StackLinkedList<'list, T> {
/// An empty linked list.
@@ -15,6 +15,12 @@ impl<'list, T> StackLinkedList<'list, T> {
StackLinkedList(Some((head, self)))
}
+ /// Attempts to return the head and tail of the list.
+ pub fn uncons(&self) -> Option<(&T, &'list StackLinkedList<'list, T>)> {
+ let (hd, tl) = self.0.as_ref()?;
+ Some((hd, tl))
+ }
+
/// Returns an iterator over the elements in the list.
pub fn iter<'iter: 'list>(&'iter self) -> impl 'iter + Iterator<Item = &'list T> {
struct Iter<'iter, 'list, T>(&'iter StackLinkedList<'list, T>);
@@ -42,3 +48,31 @@ impl<'list, T: fmt::Debug> fmt::Debug for StackLinkedList<'list, T> {
fmt.debug_list().entries(self.iter()).finish()
}
}
+
+impl<'list, T: Copy> IntoIterator for StackLinkedList<'list, T> {
+ type Item = T;
+
+ type IntoIter = OwnedIter<'list, T>;
+
+ fn into_iter(self) -> OwnedIter<'list, T> {
+ OwnedIter(self)
+ }
+}
+
+/// An (owned) iterator over a `StackLinkedList`.
+#[derive(Clone)]
+pub struct OwnedIter<'list, T>(StackLinkedList<'list, T>);
+
+impl<'list, T: Copy> Iterator for OwnedIter<'list, T> {
+ type Item = T;
+
+ fn next(&mut self) -> Option<T> {
+ match (self.0).0 {
+ Some((hd, tl)) => {
+ self.0 = *tl;
+ Some(hd)
+ }
+ None => None,
+ }
+ }
+}