Skip to main content

core/iter/adapters/
skip.rs

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