1 use crate::iter::adapters::{zip::try_get_unchecked, TrustedRandomAccess};
2 use crate::iter::{FusedIterator, TrustedLen};
5 /// An iterator that clones the elements of an underlying iterator.
7 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
8 /// documentation for more.
10 /// [`cloned`]: Iterator::cloned
11 /// [`Iterator`]: trait.Iterator.html
12 #[stable(feature = "iter_cloned", since = "1.1.0")]
13 #[must_use = "iterators are lazy and do nothing unless consumed"]
14 #[derive(Clone, Debug)]
15 pub struct Cloned<I> {
20 pub(in crate::iter) fn new(it: I) -> Cloned<I> {
25 fn clone_try_fold<T: Clone, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
26 move |acc, elt| f(acc, elt.clone())
29 #[stable(feature = "iter_cloned", since = "1.1.0")]
30 impl<'a, I, T: 'a> Iterator for Cloned<I>
32 I: Iterator<Item = &'a T>,
37 fn next(&mut self) -> Option<T> {
38 self.it.next().cloned()
41 fn size_hint(&self) -> (usize, Option<usize>) {
45 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
48 F: FnMut(B, Self::Item) -> R,
51 self.it.try_fold(init, clone_try_fold(f))
54 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
56 F: FnMut(Acc, Self::Item) -> Acc,
58 self.it.map(T::clone).fold(init, f)
61 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> T
63 Self: TrustedRandomAccess,
65 // SAFETY: the caller must uphold the contract for
66 // `Iterator::__iterator_get_unchecked`.
67 unsafe { try_get_unchecked(&mut self.it, idx).clone() }
71 #[stable(feature = "iter_cloned", since = "1.1.0")]
72 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
74 I: DoubleEndedIterator<Item = &'a T>,
77 fn next_back(&mut self) -> Option<T> {
78 self.it.next_back().cloned()
81 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
84 F: FnMut(B, Self::Item) -> R,
87 self.it.try_rfold(init, clone_try_fold(f))
90 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
92 F: FnMut(Acc, Self::Item) -> Acc,
94 self.it.map(T::clone).rfold(init, f)
98 #[stable(feature = "iter_cloned", since = "1.1.0")]
99 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
101 I: ExactSizeIterator<Item = &'a T>,
104 fn len(&self) -> usize {
108 fn is_empty(&self) -> bool {
113 #[stable(feature = "fused", since = "1.26.0")]
114 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
116 I: FusedIterator<Item = &'a T>,
122 #[unstable(feature = "trusted_random_access", issue = "none")]
123 unsafe impl<I> TrustedRandomAccess for Cloned<I>
125 I: TrustedRandomAccess,
127 const MAY_HAVE_SIDE_EFFECT: bool = true;
130 #[unstable(feature = "trusted_len", issue = "37572")]
131 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
133 I: TrustedLen<Item = &'a T>,