Skip to main content

core/iter/adapters/
copied.rs

1use crate::iter::adapters::zip::try_get_unchecked;
2use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
3use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
4use crate::mem::{MaybeUninit, SizedTypeProperties};
5use crate::num::NonZero;
6use crate::ops::Try;
7use crate::{array, ptr};
8
9/// An iterator that copies the elements of an underlying iterator.
10///
11/// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
12/// documentation for more.
13///
14/// [`copied`]: Iterator::copied
15/// [`Iterator`]: trait.Iterator.html
16#[stable(feature = "iter_copied", since = "1.36.0")]
17#[must_use = "iterators are lazy and do nothing unless consumed"]
18#[derive(Clone, Debug)]
19#[ferrocene::prevalidated]
20pub struct Copied<I> {
21    it: I,
22}
23
24impl<I> Copied<I> {
25    #[ferrocene::prevalidated]
26    pub(in crate::iter) const fn new(it: I) -> Copied<I> {
27        Copied { it }
28    }
29
30    #[doc(hidden)]
31    #[unstable(feature = "copied_into_inner", issue = "none")]
32    pub fn into_inner(self) -> I {
33        self.it
34    }
35}
36
37#[ferrocene::prevalidated]
38fn copy_fold<T: Copy, Acc>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc {
39    move |acc, &elt| f(acc, elt)
40}
41
42#[ferrocene::prevalidated]
43fn copy_try_fold<T: Copy, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
44    move |acc, &elt| f(acc, elt)
45}
46
47#[stable(feature = "iter_copied", since = "1.36.0")]
48impl<'a, I, T: 'a> Iterator for Copied<I>
49where
50    I: Iterator<Item = &'a T>,
51    T: Copy,
52{
53    type Item = T;
54
55    #[ferrocene::prevalidated]
56    fn next(&mut self) -> Option<T> {
57        self.it.next().copied()
58    }
59
60    fn next_chunk<const N: usize>(
61        &mut self,
62    ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
63    where
64        Self: Sized,
65    {
66        <I as SpecNextChunk<'_, N, T>>::spec_next_chunk(&mut self.it)
67    }
68
69    #[ferrocene::prevalidated]
70    fn size_hint(&self) -> (usize, Option<usize>) {
71        self.it.size_hint()
72    }
73
74    #[ferrocene::prevalidated]
75    #[inline]
76    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
77    where
78        Self: Sized,
79        F: FnMut(B, Self::Item) -> R,
80        R: Try<Output = B>,
81    {
82        self.it.try_fold(init, copy_try_fold(f))
83    }
84
85    #[ferrocene::prevalidated]
86    #[inline]
87    fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
88    where
89        F: FnMut(Acc, Self::Item) -> Acc,
90    {
91        self.it.fold(init, copy_fold(f))
92    }
93
94    #[ferrocene::prevalidated]
95    fn nth(&mut self, n: usize) -> Option<T> {
96        self.it.nth(n).copied()
97    }
98
99    #[ferrocene::prevalidated]
100    fn last(self) -> Option<T> {
101        self.it.last().copied()
102    }
103
104    #[ferrocene::prevalidated]
105    fn count(self) -> usize {
106        self.it.count()
107    }
108
109    #[inline]
110    #[ferrocene::prevalidated]
111    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
112        self.it.advance_by(n)
113    }
114
115    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> T
116    where
117        Self: TrustedRandomAccessNoCoerce,
118    {
119        // SAFETY: the caller must uphold the contract for
120        // `Iterator::__iterator_get_unchecked`.
121        *unsafe { try_get_unchecked(&mut self.it, idx) }
122    }
123}
124
125#[stable(feature = "iter_copied", since = "1.36.0")]
126impl<'a, I, T: 'a> DoubleEndedIterator for Copied<I>
127where
128    I: DoubleEndedIterator<Item = &'a T>,
129    T: Copy,
130{
131    #[ferrocene::prevalidated]
132    fn next_back(&mut self) -> Option<T> {
133        self.it.next_back().copied()
134    }
135
136    #[ferrocene::prevalidated]
137    #[inline]
138    fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
139    where
140        Self: Sized,
141        F: FnMut(B, Self::Item) -> R,
142        R: Try<Output = B>,
143    {
144        self.it.try_rfold(init, copy_try_fold(f))
145    }
146
147    #[ferrocene::prevalidated]
148    #[inline]
149    fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
150    where
151        F: FnMut(Acc, Self::Item) -> Acc,
152    {
153        self.it.rfold(init, copy_fold(f))
154    }
155
156    #[inline]
157    #[ferrocene::prevalidated]
158    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
159        self.it.advance_back_by(n)
160    }
161}
162
163#[stable(feature = "iter_copied", since = "1.36.0")]
164impl<'a, I, T: 'a> ExactSizeIterator for Copied<I>
165where
166    I: ExactSizeIterator<Item = &'a T>,
167    T: Copy,
168{
169    #[ferrocene::prevalidated]
170    fn len(&self) -> usize {
171        self.it.len()
172    }
173
174    #[ferrocene::prevalidated]
175    fn is_empty(&self) -> bool {
176        self.it.is_empty()
177    }
178}
179
180#[stable(feature = "iter_copied", since = "1.36.0")]
181impl<'a, I, T: 'a> FusedIterator for Copied<I>
182where
183    I: FusedIterator<Item = &'a T>,
184    T: Copy,
185{
186}
187
188#[doc(hidden)]
189#[unstable(feature = "trusted_random_access", issue = "none")]
190unsafe impl<I> TrustedRandomAccess for Copied<I> where I: TrustedRandomAccess {}
191
192#[doc(hidden)]
193#[unstable(feature = "trusted_random_access", issue = "none")]
194unsafe impl<I> TrustedRandomAccessNoCoerce for Copied<I>
195where
196    I: TrustedRandomAccessNoCoerce,
197{
198    const MAY_HAVE_SIDE_EFFECT: bool = I::MAY_HAVE_SIDE_EFFECT;
199}
200
201#[stable(feature = "iter_copied", since = "1.36.0")]
202unsafe impl<'a, I, T: 'a> TrustedLen for Copied<I>
203where
204    I: TrustedLen<Item = &'a T>,
205    T: Copy,
206{
207}
208
209trait SpecNextChunk<'a, const N: usize, T: 'a>: Iterator<Item = &'a T>
210where
211    T: Copy,
212{
213    fn spec_next_chunk(&mut self) -> Result<[T; N], array::IntoIter<T, N>>;
214}
215
216impl<'a, const N: usize, I, T: 'a> SpecNextChunk<'a, N, T> for I
217where
218    I: Iterator<Item = &'a T>,
219    T: Copy,
220{
221    default fn spec_next_chunk(&mut self) -> Result<[T; N], array::IntoIter<T, N>> {
222        array::iter_next_chunk(&mut self.copied())
223    }
224}
225
226impl<'a, const N: usize, T: 'a> SpecNextChunk<'a, N, T> for crate::slice::Iter<'a, T>
227where
228    T: Copy,
229{
230    fn spec_next_chunk(&mut self) -> Result<[T; N], array::IntoIter<T, N>> {
231        let mut raw_array = [const { MaybeUninit::uninit() }; N];
232
233        let len = self.len();
234
235        if T::IS_ZST {
236            if len < N {
237                let _ = self.advance_by(len);
238                // SAFETY: ZSTs can be conjured ex nihilo; only the amount has to be correct
239                return Err(unsafe { array::IntoIter::new_unchecked(raw_array, 0..len) });
240            }
241
242            let _ = self.advance_by(N);
243            // SAFETY: ditto
244            return Ok(unsafe { MaybeUninit::array_assume_init(raw_array) });
245        }
246
247        if len < N {
248            // SAFETY: `len` indicates that this many elements are available and we just checked that
249            // it fits into the array.
250            unsafe {
251                ptr::copy_nonoverlapping(
252                    self.as_ref().as_ptr(),
253                    raw_array.as_mut_ptr() as *mut T,
254                    len,
255                );
256                let _ = self.advance_by(len);
257                return Err(array::IntoIter::new_unchecked(raw_array, 0..len));
258            }
259        }
260
261        // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize
262        // the array.
263        unsafe {
264            ptr::copy_nonoverlapping(self.as_ref().as_ptr(), raw_array.as_mut_ptr() as *mut T, N);
265            let _ = self.advance_by(N);
266            Ok(MaybeUninit::array_assume_init(raw_array))
267        }
268    }
269}
270
271#[stable(feature = "default_iters", since = "1.70.0")]
272impl<I: Default> Default for Copied<I> {
273    /// Creates a `Copied` iterator from the default value of `I`
274    /// ```
275    /// # use core::slice;
276    /// # use core::iter::Copied;
277    /// let iter: Copied<slice::Iter<'_, u8>> = Default::default();
278    /// assert_eq!(iter.len(), 0);
279    /// ```
280    fn default() -> Self {
281        Self::new(Default::default())
282    }
283}
284
285#[unstable(issue = "none", feature = "inplace_iteration")]
286unsafe impl<I> SourceIter for Copied<I>
287where
288    I: SourceIter,
289{
290    type Source = I::Source;
291
292    #[inline]
293    unsafe fn as_inner(&mut self) -> &mut I::Source {
294        // SAFETY: unsafe function forwarding to unsafe function with the same requirements
295        unsafe { SourceIter::as_inner(&mut self.it) }
296    }
297}
298
299#[unstable(issue = "none", feature = "inplace_iteration")]
300unsafe impl<I: InPlaceIterable> InPlaceIterable for Copied<I> {
301    const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
302    const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
303}