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
use crate::{Link, List};
mod extra;
pub struct ListIterMut<'a, T> {
next_link: &'a mut Link<T>,
len: usize,
list_len: &'a mut usize,
}
impl<T> List<T> {
pub fn iter_mut(&mut self) -> ListIterMut<'_, T> {
ListIterMut {
len: self.len,
list_len: &mut self.len,
next_link: &mut self.head,
}
}
}
impl<'a, T> Iterator for ListIterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
let next_link: *mut _ = self.next_link;
unsafe {
if let Some(ref mut node) = *next_link {
let (value, next) = node.take_mut();
self.next_link = next;
self.len -= 1;
Some(value)
} else {
None
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len;
(len, Some(len))
}
}
impl<'a, T> ExactSizeIterator for ListIterMut<'a, T> {}
impl<'a, T> IntoIterator for &'a mut List<T> {
type Item = &'a mut T;
type IntoIter = ListIterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
#[test]
fn mutref_iter() {
let mut l = List::new();
for i in 1..10 {
l.push_back(i);
}
assert_eq!(l.len(), 9);
let mut acc = 0;
for v in &mut l {
acc += *v;
*v += 1;
}
assert_eq!(acc, 45);
assert_eq!(l.len(), 9);
let mut acc = 0;
for v in &mut l {
acc += *v;
*v += 1;
}
assert_eq!(acc, 54);
assert_eq!(l.len(), 9);
}