Skip to main content

core/iter/adapters/
skip.rs

1use crate::intrinsics::unlikely;
2#[cfg(not(feature = "ferrocene_subset"))]
3use crate::iter::adapters::SourceIter;
4#[cfg(not(feature = "ferrocene_subset"))]
5use crate::iter::adapters::zip::try_get_unchecked;
6#[cfg(not(feature = "ferrocene_subset"))]
7use crate::iter::{
8    FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, TrustedRandomAccess,
9    TrustedRandomAccessNoCoerce,
10};
11use crate::num::NonZero;
12use crate::ops::{ControlFlow, Try};
13
14/// An iterator that skips over `n` elements of `iter`.
15///
16/// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
17/// documentation for more.
18///
19/// [`skip`]: Iterator::skip
20/// [`Iterator`]: trait.Iterator.html
21#[derive(Clone, Debug)]
22#[must_use = "iterators are lazy and do nothing unless consumed"]
23#[stable(feature = "rust1", since = "1.0.0")]
24pub struct Skip<I> {
25    iter: I,
26    n: usize,
27}
28
29impl<I> Skip<I> {
30    pub(in crate::iter) fn new(iter: I, n: usize) -> Skip<I> {
31        Skip { iter, n }
32    }
33}
34
35#[stable(feature = "rust1", since = "1.0.0")]
36impl<I> Iterator for Skip<I>
37where
38    I: Iterator,
39{
40    type Item = <I as Iterator>::Item;
41
42    #[inline]
43    fn next(&mut self) -> Option<I::Item> {
44        if unlikely(self.n > 0) {
45            self.iter.nth(crate::mem::take(&mut self.n))
46        } else {
47            self.iter.next()
48        }
49    }
50
51    #[inline]
52    fn nth(&mut self, n: usize) -> Option<I::Item> {
53        if self.n > 0 {
54            let skip: usize = crate::mem::take(&mut self.n);
55            // Checked add to handle overflow case.
56            let n = match skip.checked_add(n) {
57                Some(nth) => nth,
58                None => {
59                    // In case of overflow, load skip value, before loading `n`.
60                    // Because the amount of elements to iterate is beyond `usize::MAX`, this
61                    // is split into two `nth` calls where the `skip` `nth` call is discarded.
62                    self.iter.nth(skip - 1)?;
63                    n
64                }
65            };
66            // Load nth element including skip.
67            self.iter.nth(n)
68        } else {
69            self.iter.nth(n)
70        }
71    }
72
73    #[inline]
74    fn count(mut self) -> usize {
75        if self.n > 0 {
76            // nth(n) skips n+1
77            if self.iter.nth(self.n - 1).is_none() {
78                return 0;
79            }
80        }
81        self.iter.count()
82    }
83
84    #[inline]
85    fn last(mut self) -> Option<I::Item> {
86        if self.n > 0 {
87            // nth(n) skips n+1
88            self.iter.nth(self.n - 1)?;
89        }
90        self.iter.last()
91    }
92
93    #[inline]
94    fn size_hint(&self) -> (usize, Option<usize>) {
95        let (lower, upper) = self.iter.size_hint();
96
97        let lower = lower.saturating_sub(self.n);
98        let upper = match upper {
99            Some(x) => Some(x.saturating_sub(self.n)),
100            None => None,
101        };
102
103        (lower, upper)
104    }
105
106    #[inline]
107    fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
108    where
109        Self: Sized,
110        Fold: FnMut(Acc, Self::Item) -> R,
111        R: Try<Output = Acc>,
112    {
113        let n = self.n;
114        self.n = 0;
115        if n > 0 {
116            // nth(n) skips n+1
117            if self.iter.nth(n - 1).is_none() {
118                return try { init };
119            }
120        }
121        self.iter.try_fold(init, fold)
122    }
123
124    #[inline]
125    fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
126    where
127        Fold: FnMut(Acc, Self::Item) -> Acc,
128    {
129        if self.n > 0 {
130            // nth(n) skips n+1
131            if self.iter.nth(self.n - 1).is_none() {
132                return init;
133            }
134        }
135        self.iter.fold(init, fold)
136    }
137
138    #[inline]
139    #[rustc_inherit_overflow_checks]
140    fn advance_by(&mut self, mut n: usize) -> Result<(), NonZero<usize>> {
141        let skip_inner = self.n;
142        let skip_and_advance = skip_inner.saturating_add(n);
143
144        let remainder = match self.iter.advance_by(skip_and_advance) {
145            Ok(()) => 0,
146            Err(n) => n.get(),
147        };
148        let advanced_inner = skip_and_advance - remainder;
149        n -= advanced_inner.saturating_sub(skip_inner);
150        self.n = self.n.saturating_sub(advanced_inner);
151
152        // skip_and_advance may have saturated
153        if unlikely(remainder == 0 && n > 0) {
154            n = match self.iter.advance_by(n) {
155                Ok(()) => 0,
156                Err(n) => n.get(),
157            }
158        }
159
160        NonZero::new(n).map_or(Ok(()), Err)
161    }
162
163    #[doc(hidden)]
164    #[cfg(not(feature = "ferrocene_subset"))]
165    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item
166    where
167        Self: TrustedRandomAccessNoCoerce,
168    {
169        // SAFETY: the caller must uphold the contract for
170        // `Iterator::__iterator_get_unchecked`.
171        //
172        // Dropping the skipped prefix when index 0 is passed is safe
173        // since
174        // * the caller passing index 0 means that the inner iterator has more items than `self.n`
175        // * TRA contract requires that get_unchecked will only be called once
176        //   (unless elements are copyable)
177        // * it does not conflict with in-place iteration since index 0 must be accessed
178        //   before something is written into the storage used by the prefix
179        unsafe {
180            if Self::MAY_HAVE_SIDE_EFFECT && idx == 0 {
181                for skipped_idx in 0..self.n {
182                    drop(try_get_unchecked(&mut self.iter, skipped_idx));
183                }
184            }
185
186            try_get_unchecked(&mut self.iter, idx + self.n)
187        }
188    }
189}
190
191#[stable(feature = "rust1", since = "1.0.0")]
192impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
193
194#[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
195impl<I> DoubleEndedIterator for Skip<I>
196where
197    I: DoubleEndedIterator + ExactSizeIterator,
198{
199    fn next_back(&mut self) -> Option<Self::Item> {
200        if self.len() > 0 { self.iter.next_back() } else { None }
201    }
202
203    #[inline]
204    fn nth_back(&mut self, n: usize) -> Option<I::Item> {
205        let len = self.len();
206        if n < len {
207            self.iter.nth_back(n)
208        } else {
209            if len > 0 {
210                // consume the original iterator
211                self.iter.nth_back(len - 1);
212            }
213            None
214        }
215    }
216
217    fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
218    where
219        Self: Sized,
220        Fold: FnMut(Acc, Self::Item) -> R,
221        R: Try<Output = Acc>,
222    {
223        fn check<T, Acc, R: Try<Output = Acc>>(
224            mut n: usize,
225            mut fold: impl FnMut(Acc, T) -> R,
226        ) -> impl FnMut(Acc, T) -> ControlFlow<R, Acc> {
227            move |acc, x| {
228                n -= 1;
229                let r = fold(acc, x);
230                if n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
231            }
232        }
233
234        let n = self.len();
235        if n == 0 { try { init } } else { self.iter.try_rfold(init, check(n, fold)).into_try() }
236    }
237
238    impl_fold_via_try_fold! { rfold -> try_rfold }
239
240    #[inline]
241    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
242        let min = crate::cmp::min(self.len(), n);
243        let rem = self.iter.advance_back_by(min);
244        assert!(rem.is_ok(), "ExactSizeIterator contract violation");
245        NonZero::new(n - min).map_or(Ok(()), Err)
246    }
247}
248
249#[stable(feature = "fused", since = "1.26.0")]
250#[cfg(not(feature = "ferrocene_subset"))]
251impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
252
253#[unstable(issue = "none", feature = "trusted_fused")]
254#[cfg(not(feature = "ferrocene_subset"))]
255unsafe impl<I: TrustedFused> TrustedFused for Skip<I> {}
256
257#[unstable(issue = "none", feature = "inplace_iteration")]
258#[cfg(not(feature = "ferrocene_subset"))]
259unsafe impl<I> SourceIter for Skip<I>
260where
261    I: SourceIter,
262{
263    type Source = I::Source;
264
265    #[inline]
266    unsafe fn as_inner(&mut self) -> &mut I::Source {
267        // SAFETY: unsafe function forwarding to unsafe function with the same requirements
268        unsafe { SourceIter::as_inner(&mut self.iter) }
269    }
270}
271
272#[unstable(issue = "none", feature = "inplace_iteration")]
273#[cfg(not(feature = "ferrocene_subset"))]
274unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> {
275    const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
276    const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
277}
278
279#[doc(hidden)]
280#[unstable(feature = "trusted_random_access", issue = "none")]
281#[cfg(not(feature = "ferrocene_subset"))]
282unsafe impl<I> TrustedRandomAccess for Skip<I> where I: TrustedRandomAccess {}
283
284#[doc(hidden)]
285#[unstable(feature = "trusted_random_access", issue = "none")]
286#[cfg(not(feature = "ferrocene_subset"))]
287unsafe impl<I> TrustedRandomAccessNoCoerce for Skip<I>
288where
289    I: TrustedRandomAccessNoCoerce,
290{
291    const MAY_HAVE_SIDE_EFFECT: bool = I::MAY_HAVE_SIDE_EFFECT;
292}
293
294// SAFETY: This adapter is shortening. TrustedLen requires the upper bound to be calculated correctly.
295// These requirements can only be satisfied when the upper bound of the inner iterator's upper
296// bound is never `None`. I: TrustedRandomAccess happens to provide this guarantee while
297// I: TrustedLen would not.
298#[unstable(feature = "trusted_len", issue = "37572")]
299#[cfg(not(feature = "ferrocene_subset"))]
300unsafe impl<I> TrustedLen for Skip<I> where I: Iterator + TrustedRandomAccess {}