You can now iterate a list

main
ondra05 2022-07-21 12:04:56 +02:00
parent 7a7bdbca7a
commit 4a4aca2366
1 changed files with 43 additions and 0 deletions

View File

@ -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<Self::Item> {
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<Self::Item> {
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,
}
}
}