gat_lending_iterator/to_lending/
lend_refs.rs1use crate::LendingIterator;
2
3#[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>
22 = &'a I::Item
23 where
24 Self: 'a;
25
26 fn next(&mut self) -> Option<Self::Item<'_>> {
27 self.item = self.iter.next();
28 self.item.as_ref()
29 }
30}
31#[cfg(test)]
32mod test {
33 use crate::{LendingIterator, ToLendingIterator};
34 #[derive(Clone, Eq, PartialEq, Debug)]
35 struct Foo(usize);
36 struct W {
37 x: Foo,
38 }
39 impl LendingIterator for W {
40 type Item<'a>
41 = &'a Foo
42 where
43 Self: 'a;
44 fn next(&mut self) -> Option<Self::Item<'_>> {
45 self.x.0 += 1;
46 Some(&self.x)
47 }
48 }
49 #[test]
50 fn test() {
51 let mut xs = Vec::new();
52 test_helper().take(3).for_each(|x: &Foo| {
53 xs.push(x.clone());
54 });
55 assert_eq!(xs, vec![Foo(0), Foo(1), Foo(2)]);
56 }
57
58 fn test_helper() -> impl for<'a> LendingIterator<Item<'a> = &'a Foo> {
59 let w = W { x: Foo(0) };
60 std::iter::once(Foo(0)).lend_refs().chain(w)
61 }
62
63 #[allow(clippy::trivially_copy_pass_by_ref)]
64 fn double_ref_i32(x: &i32) -> i32 {
65 x * 2
66 }
67
68 #[test]
69 fn lend_refs_basic() {
70 let result: Vec<_> = vec![1, 2, 3]
71 .lend_refs()
72 .map(double_ref_i32)
73 .into_iter()
74 .collect();
75 assert_eq!(result, vec![2, 4, 6]);
76 }
77}