gat_lending_iterator/to_lending/
lend_refs_mut.rs

1use crate::LendingIterator;
2
3/// A lending iterator that given an iterator, lends
4/// mutable references to the given iterator's items.
5#[derive(Clone)]
6pub struct LendRefsMut<I: Iterator> {
7    item: Option<I::Item>,
8    iter: I,
9}
10
11impl<I: Iterator> LendRefsMut<I> {
12    pub(crate) fn new(iter: I) -> LendRefsMut<I> {
13        LendRefsMut { item: None, iter }
14    }
15}
16
17impl<I: Iterator> LendingIterator for LendRefsMut<I> {
18    type Item<'a> = &'a mut I::Item where Self: 'a;
19
20    fn next(&mut self) -> Option<Self::Item<'_>> {
21        self.item = self.iter.next();
22        self.item.as_mut()
23    }
24}
25
26#[cfg(test)]
27mod test {
28    use crate::{LendingIterator, ToLendingIterator};
29    #[derive(Clone, Eq, PartialEq, Debug)]
30    struct Foo(usize);
31    struct W {
32        x: Foo,
33    }
34
35    impl LendingIterator for W {
36        type Item<'a> = &'a mut Foo where Self: 'a;
37        fn next(&mut self) -> Option<Self::Item<'_>> {
38            self.x.0 += 1;
39            Some(&mut self.x)
40        }
41    }
42
43    #[test]
44    fn test() {
45        let mut xs = Vec::new();
46        test_helper().take(3).for_each(|x: &mut Foo| {
47            x.0 += 2;
48            xs.push(x.clone());
49        });
50        assert_eq!(xs, vec![Foo(2), Foo(3), Foo(6)]);
51    }
52
53    fn test_helper() -> impl for<'a> LendingIterator<Item<'a> = &'a mut Foo> {
54        let w = W { x: Foo(0) };
55        std::iter::once(Foo(0)).lend_refs_mut().chain(w)
56    }
57}