Added exemplary unit test for iter_mut().
[rust-101.git] / solutions / src / list.rs
index 180627dcb6df7102484b2e79289937122a026f32..1c794fc3f81aa1da1849ce1ae1b620fe63ac8620 100644 (file)
@@ -1,4 +1,3 @@
-
 use std::ptr;
 use std::mem;
 use std::marker::PhantomData;
@@ -54,6 +53,8 @@ impl<T> LinkedList<T> {
             if new_last.is_null() {
                 // The list is now empty.
                 self.first = new_last;
+            } else {
+                unsafe { (*new_last).next = ptr::null_mut() };
             }
             let last = unsafe { raw_into_box(last) } ;
             Some(last.data)
@@ -87,6 +88,8 @@ impl<T> LinkedList<T> {
             if new_first.is_null() {
                 // The list is now empty.
                 self.last = new_first;
+            } else {
+                unsafe { (*new_first).prev = ptr::null_mut() };
             }
             let first = unsafe { raw_into_box(first) } ;
             Some(first.data)
@@ -102,7 +105,7 @@ impl<T> LinkedList<T> {
         }
     }
 
-    pub fn iter_mut(&self) -> IterMut<T> {
+    pub fn iter_mut(&mut self) -> IterMut<T> {
         IterMut { next: self.first, _marker: PhantomData  }
     }
 }
@@ -201,4 +204,20 @@ mod tests {
         }
         assert_eq!(count.count.get(), 20);
     }
+
+    #[test]
+    fn test_iter_mut() {
+        let mut l = LinkedList::<i32>::new();
+        for i in 0..5 {
+            l.push_back(i);
+        }
+
+        assert_eq!(l.pop_front(), Some(0));
+        assert_eq!(l.pop_back(), Some(4));
+
+        for (n, i) in l.iter_mut().enumerate() {
+            *i-=1;
+            assert_eq!(n as i32, *i);
+        }
+    }
 }