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
use crate::LendingIterator;

/// A lending iterator that given an iterator, lends
/// mutable references to the given iterator's items.
#[derive(Clone)]
pub struct LendRefsMut<I: Iterator> {
    item: Option<I::Item>,
    iter: I,
}

impl<I: Iterator> LendRefsMut<I> {
    pub(crate) fn new(iter: I) -> LendRefsMut<I> {
        LendRefsMut { item: None, iter }
    }
}

impl<I: Iterator> LendingIterator for LendRefsMut<I> {
    type Item<'a> = &'a mut I::Item where Self: 'a;

    fn next(&mut self) -> Option<Self::Item<'_>> {
        self.item = self.iter.next();
        self.item.as_mut()
    }
}

#[cfg(test)]
mod test {
    use crate::{LendingIterator, ToLendingIterator};
    #[derive(Clone, Eq, PartialEq, Debug)]
    struct Foo(usize);
    struct W {
        x: Foo,
    }

    impl LendingIterator for W {
        type Item<'a> = &'a mut Foo where Self: 'a;
        fn next(&mut self) -> Option<Self::Item<'_>> {
            self.x.0 += 1;
            Some(&mut self.x)
        }
    }

    #[test]
    fn test() {
        let mut xs = Vec::new();
        test_helper().take(3).for_each(|x: &mut Foo| {
            x.0 += 2;
            xs.push(x.clone());
        });
        assert_eq!(xs, vec![Foo(2), Foo(3), Foo(6)]);
    }

    fn test_helper() -> impl for<'a> LendingIterator<Item<'a> = &'a mut Foo> {
        let w = W { x: Foo(0) };
        std::iter::once(Foo(0)).lend_refs_mut().chain(w)
    }
}