1 use crate::iter::adapters::{zip::try_get_unchecked, TrustedRandomAccess};
2 use crate::iter::{FusedIterator, TrustedLen};
5 /// An iterator that copies the elements of an underlying iterator.
7 /// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
8 /// documentation for more.
10 /// [`copied`]: Iterator::copied
11 /// [`Iterator`]: trait.Iterator.html
12 #[stable(feature = "iter_copied", since = "1.36.0")]
13 #[must_use = "iterators are lazy and do nothing unless consumed"]
14 #[derive(Clone, Debug)]
15 pub struct Copied<I> {
20 pub(in crate::iter) fn new(it: I) -> Copied<I> {
25 fn copy_fold<T: Copy, Acc>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc {
26 move |acc, &elt| f(acc, elt)
29 fn copy_try_fold<T: Copy, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
30 move |acc, &elt| f(acc, elt)
33 #[stable(feature = "iter_copied", since = "1.36.0")]
34 impl<'a, I, T: 'a> Iterator for Copied<I>
36 I: Iterator<Item = &'a T>,
41 fn next(&mut self) -> Option<T> {
42 self.it.next().copied()
45 fn size_hint(&self) -> (usize, Option<usize>) {
49 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
52 F: FnMut(B, Self::Item) -> R,
55 self.it.try_fold(init, copy_try_fold(f))
58 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
60 F: FnMut(Acc, Self::Item) -> Acc,
62 self.it.fold(init, copy_fold(f))
65 fn nth(&mut self, n: usize) -> Option<T> {
66 self.it.nth(n).copied()
69 fn last(self) -> Option<T> {
70 self.it.last().copied()
73 fn count(self) -> usize {
77 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> T
79 Self: TrustedRandomAccess,
81 // SAFETY: the caller must uphold the contract for
82 // `Iterator::__iterator_get_unchecked`.
83 *unsafe { try_get_unchecked(&mut self.it, idx) }
87 #[stable(feature = "iter_copied", since = "1.36.0")]
88 impl<'a, I, T: 'a> DoubleEndedIterator for Copied<I>
90 I: DoubleEndedIterator<Item = &'a T>,
93 fn next_back(&mut self) -> Option<T> {
94 self.it.next_back().copied()
97 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
100 F: FnMut(B, Self::Item) -> R,
103 self.it.try_rfold(init, copy_try_fold(f))
106 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
108 F: FnMut(Acc, Self::Item) -> Acc,
110 self.it.rfold(init, copy_fold(f))
114 #[stable(feature = "iter_copied", since = "1.36.0")]
115 impl<'a, I, T: 'a> ExactSizeIterator for Copied<I>
117 I: ExactSizeIterator<Item = &'a T>,
120 fn len(&self) -> usize {
124 fn is_empty(&self) -> bool {
129 #[stable(feature = "iter_copied", since = "1.36.0")]
130 impl<'a, I, T: 'a> FusedIterator for Copied<I>
132 I: FusedIterator<Item = &'a T>,
138 #[unstable(feature = "trusted_random_access", issue = "none")]
139 unsafe impl<I> TrustedRandomAccess for Copied<I>
141 I: TrustedRandomAccess,
144 fn may_have_side_effect() -> bool {
145 I::may_have_side_effect()
149 #[stable(feature = "iter_copied", since = "1.36.0")]
150 unsafe impl<'a, I, T: 'a> TrustedLen for Copied<I>
152 I: TrustedLen<Item = &'a T>,