From fd6b22a2f36f13d2bba293f16770228f3189e836 Mon Sep 17 00:00:00 2001 From: Quentin Legot Date: Fri, 17 Feb 2023 09:45:47 +0100 Subject: [PATCH] Improve list by adding iterator trait --- src/utility/list.rs | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/src/utility/list.rs b/src/utility/list.rs index 6b0ddbb..46f5557 100644 --- a/src/utility/list.rs +++ b/src/utility/list.rs @@ -77,7 +77,7 @@ impl DoublyLinkedList { } } - /// Remove the item at the end of the list + /// Retrieve and remove the item at the end of the list pub fn pop_back(&mut self) -> Option { self.tail.take().map(|prev_tail| { self.size -= 1; @@ -94,7 +94,7 @@ impl DoublyLinkedList { }) } - /// Remove the item at the start of the list + /// Retrieve and remove the item at the start of the list pub fn pop_front(&mut self) -> Option { self.head.take().map(|prev_head| { self.size -= 1; @@ -124,6 +124,43 @@ impl Drop for DoublyLinkedList { } } +impl IntoIterator for DoublyLinkedList { + type Item = as Iterator>::Item; + + type IntoIter = ListIterator; + + fn into_iter(self) -> Self::IntoIter { + Self::IntoIter::new(self) + } +} + +pub struct ListIterator { + list: DoublyLinkedList, +} + +impl ListIterator { + fn new(list: DoublyLinkedList) -> Self { + Self { list } + } +} + +impl Iterator for ListIterator { + type Item = T; + + fn next(&mut self) -> Option { + self.list.pop_front() + } +} + +impl DoubleEndedIterator for ListIterator { + fn next_back(&mut self) -> Option { + self.list.pop_back() + } +} + +pub type List = DoublyLinkedList; +pub type ListInt = List; + #[cfg(test)] mod test { @@ -138,5 +175,4 @@ mod test { assert_eq!(list.pop_front().unwrap(), 5); } - } \ No newline at end of file