gat_lending_iterator/to_lending/
lend_refs.rs

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