diff --git a/src/lib.rs b/src/lib.rs index 4ea49cb..8e45b5e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -883,6 +883,46 @@ where } } +impl IntoIterator for IndexList { + type Item = T; + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + let next_index = self.head; + + IntoIter { + list: self, + next_index, + } + } +} + +pub struct IntoIter { + list: IndexList, + next_index: Option, +} + +impl Iterator for IntoIter { + type Item = T; + + fn next(&mut self) -> Option { + 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, @@ -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();