From e5e192a1426e5bc74002fa6f8e60359b5ea61085 Mon Sep 17 00:00:00 2001 From: Erin Date: Thu, 21 Jul 2022 12:04:56 +0200 Subject: [PATCH] You can now iterate a list --- src/list.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/list.rs b/src/list.rs index dec4527..92c777e 100644 --- a/src/list.rs +++ b/src/list.rs @@ -14,4 +14,47 @@ impl<'a> List<'a> { .rev() .fold(Self::Nil, |list, next| Self::Cons(next, Box::new(list))) } + + pub fn iter(&self) -> Iter<'_, '_> { + Iter(self) + } +} + +pub struct Iter<'l, 'v>(&'l List<'v>); +impl<'l, 'v> Iterator for Iter<'l, 'v> { + type Item = &'l Value<'v>; + + fn next(&mut self) -> Option { + match self.0 { + List::Cons(head, rest) => { + self.0 = &**rest; + Some(head) + } + List::Nil => None, + } + } +} + +impl<'a> IntoIterator for List<'a> { + type Item = Value<'a>; + type IntoIter = IntoIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + IntoIter(self) + } +} + +pub struct IntoIter<'a>(List<'a>); +impl<'a> Iterator for IntoIter<'a> { + type Item = Value<'a>; + + fn next(&mut self) -> Option { + match std::mem::take(&mut self.0) { + List::Cons(first, mut rest) => { + std::mem::swap(&mut self.0, rest.as_mut()); + Some(first) + } + List::Nil => None, + } + } }