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
use std::ops::Deref;

use crate::LendingIterator;

/// A lending iterator that clones the elements of an underlying lending iterator.
///
/// This `struct` is created by the [`cloned`] method on [`LendingIterator`]. See
/// its documentation for more.
///
/// [`LendingIterator`]: crate::LendingIterator
/// [`cloned`]: crate::LendingIterator::cloned
#[derive(Clone, Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Cloned<I> {
    iter: I,
}

impl<I> Cloned<I> {
    pub(crate) fn new(iter: I) -> Cloned<I> {
        Cloned { iter }
    }
}

impl<I> LendingIterator for Cloned<I>
where
    I: LendingIterator,
    for<'a> I::Item<'a>: Deref,
    for<'a> <I::Item<'a> as Deref>::Target: Clone,
{
    type Item<'a> = <I::Item<'a> as Deref>::Target
    where
        Self: 'a;

    fn next(&mut self) -> Option<Self::Item<'_>> {
        self.iter.next().map(|item| item.deref().clone())
    }
}

pub struct IntoIter<I> {
    iter: I,
}

impl<I, T> Iterator for IntoIter<I>
where
    I: LendingIterator,
    for<'a> I::Item<'a>: Deref<Target = T>,
    T: Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|item| item.deref().clone())
    }
}

impl<I, T> IntoIterator for Cloned<I>
where
    I: LendingIterator,
    for<'a> I::Item<'a>: Deref<Target = T>,
    T: Clone,
{
    type Item = T;
    type IntoIter = IntoIter<I>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter { iter: self.iter }
    }
}