Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement IntoIterator for IndexList<T> #11

Merged
merged 1 commit into from
Sep 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,46 @@ where
}
}

impl<T> IntoIterator for IndexList<T> {
type Item = T;
type IntoIter = IntoIter<T>;

fn into_iter(self) -> Self::IntoIter {
let next_index = self.head;

IntoIter {
list: self,
next_index,
}
}
}

pub struct IntoIter<T> {
list: IndexList<T>,
next_index: Option<usize>,
}

impl<T> Iterator for IntoIter<T> {
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
let next_index = self.next_index?;
let entry = std::mem::replace(
&mut self.list.contents[next_index],
Entry::Free { next_free: None },
);

match entry {
Entry::Free { .. } => panic!("Corrupted list"),
Entry::Occupied(e) => {
self.next_index = e.next;

Some(e.item)
}
}
}
}

struct Iter<'a, T>
where
T: 'a,
Expand Down Expand Up @@ -1149,6 +1189,24 @@ mod tests {
assert!(list.remove(five_index).is_none());
}

#[test]
fn into_iter() {
let mut list = IndexList::new();

list.push_back(5);
let ten = list.push_back(10);
list.push_back(15);

list.remove(ten);

let mut iter = list.into_iter();

assert_eq!(iter.next().unwrap(), 5);
assert_eq!(iter.next().unwrap(), 15);

assert!(iter.next().is_none());
}

#[test]
fn iter() {
let mut list = IndexList::new();
Expand Down