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, + } + } }