1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! A set of iterator types for a [`LinkedList`]

use std::{iter::FusedIterator, ptr::NonNull};

use crate::{LinkedList, Node};

impl<T> IntoIterator for LinkedList<T> {
    type IntoIter = IntoIter<T>;
    type Item = T;
    fn into_iter(self) -> Self::IntoIter {
        IntoIter(self)
    }
}

/// Owned iterator of a [`LinkedList`]
pub struct IntoIter<T>(pub(crate) LinkedList<T>);

impl<T> FusedIterator for IntoIter<T> {}

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

    fn next(&mut self) -> Option<Self::Item> {
        self.0.pop_front()
    }
}

impl<'a, T> IntoIterator for &'a LinkedList<T> {
    type IntoIter = Iter<'a, T>;
    type Item = &'a T;
    fn into_iter(self) -> Self::IntoIter {
        Iter(&self.0)
    }
}

/// Borrowed iterator of a [`LinkedList`]
#[derive(Clone)]
pub struct Iter<'a, T>(pub(crate) &'a Option<NonNull<Node<T>>>);

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.map(|node| unsafe {
            let node = node.as_ref();
            self.0 = &node.next.0;
            &node.value
        })
    }
}

impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
    type IntoIter = IterMut<'a, T>;
    type Item = &'a mut T;
    fn into_iter(self) -> Self::IntoIter {
        IterMut(&mut self.0)
    }
}

/// Mutable iterator of a [`LinkedList`]
pub struct IterMut<'a, T>(pub(crate) &'a mut Option<NonNull<Node<T>>>);

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.map(|mut node| unsafe {
            let node = node.as_mut();
            self.0 = &mut node.next.0;
            &mut node.value
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::LinkedList;

    #[test]
    fn iter() {
        let ll = LinkedList::from_iter([1, 2, 3]);

        assert_eq!(ll.iter().cloned().collect::<Vec<_>>(), vec![1, 2, 3]);
    }

    #[test]
    fn iter_mut() {
        let mut ll = LinkedList::from_iter([1, 2, 3]);
        ll.iter_mut().for_each(|i| *i *= 2);

        assert_eq!(ll.into_iter().collect::<Vec<_>>(), [2, 4, 6]);
    }
}