Skip to main content

core/range/
iter.rs

1use crate::iter::{
2    FusedIterator, Step, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep,
3};
4use crate::num::NonZero;
5use crate::range::{Range, RangeFrom, RangeInclusive, legacy};
6use crate::{intrinsics, mem};
7
8/// By-value [`Range`] iterator.
9#[stable(feature = "new_range_api", since = "CURRENT_RUSTC_VERSION")]
10#[derive(Debug, Clone)]
11pub struct RangeIter<A>(legacy::Range<A>);
12
13impl<A> RangeIter<A> {
14    #[unstable(feature = "new_range_remainder", issue = "154458")]
15    /// Returns the remainder of the range being iterated over.
16    ///
17    /// # Examples
18    ///
19    /// ```
20    /// #![feature(new_range_remainder)]
21    ///
22    /// let range = core::range::Range::from(3..11);
23    /// let mut iter = range.into_iter();
24    /// assert_eq!(iter.clone().remainder(), range);
25    /// iter.next();
26    /// assert_eq!(iter.clone().remainder(), core::range::Range::from(4..11));
27    /// iter.by_ref().for_each(drop);
28    /// assert!(iter.remainder().is_empty());
29    /// ```
30    pub fn remainder(self) -> Range<A> {
31        Range { start: self.0.start, end: self.0.end }
32    }
33}
34
35/// Safety: This macro must only be used on types that are `Copy` and result in ranges
36/// which have an exact `size_hint()` where the upper bound must not be `None`.
37macro_rules! unsafe_range_trusted_random_access_impl {
38    ($($t:ty)*) => ($(
39        #[doc(hidden)]
40        #[unstable(feature = "trusted_random_access", issue = "none")]
41        unsafe impl TrustedRandomAccess for RangeIter<$t> {}
42
43        #[doc(hidden)]
44        #[unstable(feature = "trusted_random_access", issue = "none")]
45        unsafe impl TrustedRandomAccessNoCoerce for RangeIter<$t> {
46            const MAY_HAVE_SIDE_EFFECT: bool = false;
47        }
48    )*)
49}
50
51unsafe_range_trusted_random_access_impl! {
52    usize u8 u16
53    isize i8 i16
54}
55
56#[cfg(target_pointer_width = "32")]
57unsafe_range_trusted_random_access_impl! {
58    u32 i32
59}
60
61#[cfg(target_pointer_width = "64")]
62unsafe_range_trusted_random_access_impl! {
63    u32 i32
64    u64 i64
65}
66
67#[stable(feature = "new_range_api", since = "CURRENT_RUSTC_VERSION")]
68impl<A: Step> Iterator for RangeIter<A> {
69    type Item = A;
70
71    #[inline]
72    fn next(&mut self) -> Option<A> {
73        self.0.next()
74    }
75
76    #[inline]
77    fn size_hint(&self) -> (usize, Option<usize>) {
78        self.0.size_hint()
79    }
80
81    #[inline]
82    fn count(self) -> usize {
83        self.0.count()
84    }
85
86    #[inline]
87    fn nth(&mut self, n: usize) -> Option<A> {
88        self.0.nth(n)
89    }
90
91    #[inline]
92    fn last(self) -> Option<A> {
93        self.0.last()
94    }
95
96    #[inline]
97    fn min(self) -> Option<A>
98    where
99        A: Ord,
100    {
101        self.0.min()
102    }
103
104    #[inline]
105    fn max(self) -> Option<A>
106    where
107        A: Ord,
108    {
109        self.0.max()
110    }
111
112    #[inline]
113    fn is_sorted(self) -> bool {
114        true
115    }
116
117    #[inline]
118    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
119        self.0.advance_by(n)
120    }
121
122    #[inline]
123    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item
124    where
125        Self: TrustedRandomAccessNoCoerce,
126    {
127        // SAFETY: The TrustedRandomAccess contract requires that callers only pass an index
128        // that is in bounds.
129        // Additionally Self: TrustedRandomAccess is only implemented for Copy types
130        // which means even repeated reads of the same index would be safe.
131        unsafe { Step::forward_unchecked(self.0.start.clone(), idx) }
132    }
133}
134
135#[stable(feature = "new_range_api", since = "CURRENT_RUSTC_VERSION")]
136impl<A: Step> DoubleEndedIterator for RangeIter<A> {
137    #[inline]
138    fn next_back(&mut self) -> Option<A> {
139        self.0.next_back()
140    }
141
142    #[inline]
143    fn nth_back(&mut self, n: usize) -> Option<A> {
144        self.0.nth_back(n)
145    }
146
147    #[inline]
148    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
149        self.0.advance_back_by(n)
150    }
151}
152
153#[unstable(feature = "trusted_len", issue = "37572")]
154unsafe impl<A: TrustedStep> TrustedLen for RangeIter<A> {}
155
156#[stable(feature = "new_range_api", since = "CURRENT_RUSTC_VERSION")]
157impl<A: Step> FusedIterator for RangeIter<A> {}
158
159#[stable(feature = "new_range_api", since = "CURRENT_RUSTC_VERSION")]
160impl<A: Step> IntoIterator for Range<A> {
161    type Item = A;
162    type IntoIter = RangeIter<A>;
163
164    fn into_iter(self) -> Self::IntoIter {
165        RangeIter(self.into())
166    }
167}
168
169/// By-value [`RangeInclusive`] iterator.
170#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
171#[derive(Debug, Clone)]
172pub struct RangeInclusiveIter<A>(legacy::RangeInclusive<A>);
173
174impl<A: Step> RangeInclusiveIter<A> {
175    /// Returns the remainder of the range being iterated over.
176    ///
177    /// If the iterator is exhausted or empty, returns `None`.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// #![feature(new_range_remainder)]
183    ///
184    /// let range = core::range::RangeInclusive::from(3..=11);
185    /// let mut iter = range.into_iter();
186    /// assert_eq!(iter.clone().remainder().unwrap(), range);
187    /// iter.next();
188    /// assert_eq!(iter.clone().remainder().unwrap(), core::range::RangeInclusive::from(4..=11));
189    /// iter.by_ref().for_each(drop);
190    /// assert!(iter.remainder().is_none());
191    /// ```
192    #[unstable(feature = "new_range_remainder", issue = "154458")]
193    pub fn remainder(self) -> Option<RangeInclusive<A>> {
194        if self.0.is_empty() {
195            return None;
196        }
197
198        Some(RangeInclusive { start: self.0.start, last: self.0.end })
199    }
200}
201
202#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
203impl<A: Step> Iterator for RangeInclusiveIter<A> {
204    type Item = A;
205
206    #[inline]
207    fn next(&mut self) -> Option<A> {
208        self.0.next()
209    }
210
211    #[inline]
212    fn size_hint(&self) -> (usize, Option<usize>) {
213        self.0.size_hint()
214    }
215
216    #[inline]
217    fn count(self) -> usize {
218        self.0.count()
219    }
220
221    #[inline]
222    fn nth(&mut self, n: usize) -> Option<A> {
223        self.0.nth(n)
224    }
225
226    #[inline]
227    fn last(self) -> Option<A> {
228        self.0.last()
229    }
230
231    #[inline]
232    fn min(self) -> Option<A>
233    where
234        A: Ord,
235    {
236        self.0.min()
237    }
238
239    #[inline]
240    fn max(self) -> Option<A>
241    where
242        A: Ord,
243    {
244        self.0.max()
245    }
246
247    #[inline]
248    fn is_sorted(self) -> bool {
249        true
250    }
251
252    #[inline]
253    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
254        self.0.advance_by(n)
255    }
256}
257
258#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
259impl<A: Step> DoubleEndedIterator for RangeInclusiveIter<A> {
260    #[inline]
261    fn next_back(&mut self) -> Option<A> {
262        self.0.next_back()
263    }
264
265    #[inline]
266    fn nth_back(&mut self, n: usize) -> Option<A> {
267        self.0.nth_back(n)
268    }
269
270    #[inline]
271    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
272        self.0.advance_back_by(n)
273    }
274}
275
276#[unstable(feature = "trusted_len", issue = "37572")]
277unsafe impl<A: TrustedStep> TrustedLen for RangeInclusiveIter<A> {}
278
279#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
280impl<A: Step> FusedIterator for RangeInclusiveIter<A> {}
281
282#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
283impl<A: Step> IntoIterator for RangeInclusive<A> {
284    type Item = A;
285    type IntoIter = RangeInclusiveIter<A>;
286
287    fn into_iter(self) -> Self::IntoIter {
288        RangeInclusiveIter(self.into())
289    }
290}
291
292// These macros generate `ExactSizeIterator` impls for various range types.
293//
294// * `ExactSizeIterator::len` is required to always return an exact `usize`,
295//   so no range can be longer than `usize::MAX`.
296// * For integer types in `Range<_>` this is the case for types narrower than or as wide as `usize`.
297//   For integer types in `RangeInclusive<_>`
298//   this is the case for types *strictly narrower* than `usize`
299//   since e.g. `(0..=u64::MAX).len()` would be `u64::MAX + 1`.
300macro_rules! range_exact_iter_impl {
301    ($($t:ty)*) => ($(
302        #[stable(feature = "new_range_api", since = "CURRENT_RUSTC_VERSION")]
303        impl ExactSizeIterator for RangeIter<$t> { }
304    )*)
305}
306
307macro_rules! range_incl_exact_iter_impl {
308    ($($t:ty)*) => ($(
309        #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
310        impl ExactSizeIterator for RangeInclusiveIter<$t> { }
311    )*)
312}
313
314range_exact_iter_impl! {
315    usize u8 u16
316    isize i8 i16
317}
318
319range_incl_exact_iter_impl! {
320    u8
321    i8
322}
323
324/// By-value [`RangeFrom`] iterator.
325#[stable(feature = "new_range_from_api", since = "CURRENT_RUSTC_VERSION")]
326#[derive(Debug, Clone)]
327pub struct RangeFromIter<A> {
328    start: A,
329    /// Whether the maximum value of the iterator has yielded.
330    /// Only used when overflow checks are enabled.
331    exhausted: bool,
332}
333
334impl<A: Step> RangeFromIter<A> {
335    /// Returns the remainder of the range being iterated over.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// #![feature(new_range_remainder)]
341    ///
342    /// let range = core::range::RangeFrom::from(3..);
343    /// let mut iter = range.into_iter();
344    /// assert_eq!(iter.clone().remainder(), range);
345    /// iter.next();
346    /// assert_eq!(iter.remainder(), core::range::RangeFrom::from(4..));
347    /// ```
348    #[inline]
349    #[rustc_inherit_overflow_checks]
350    #[unstable(feature = "new_range_remainder", issue = "154458")]
351    pub fn remainder(self) -> RangeFrom<A> {
352        // Need to handle this case even if overflow-checks are disabled,
353        // because a `RangeFromIter` could be exhausted in a crate with
354        // overflow-checks enabled, but then passed to a crate with them
355        // disabled before this is called.
356        if self.exhausted {
357            return RangeFrom { start: Step::forward(self.start, 1) };
358        }
359
360        RangeFrom { start: self.start }
361    }
362}
363
364#[stable(feature = "new_range_from_api", since = "CURRENT_RUSTC_VERSION")]
365impl<A: Step> Iterator for RangeFromIter<A> {
366    type Item = A;
367
368    #[inline]
369    #[rustc_inherit_overflow_checks]
370    fn next(&mut self) -> Option<A> {
371        if self.exhausted {
372            // This should panic if overflow checks are enabled, since
373            // `forward_checked` returned `None` in prior iteration.
374            self.start = Step::forward(self.start.clone(), 1);
375
376            // If we get here, if means this iterator was exhausted by a crate
377            // with overflow-checks enabled, but now we're iterating in a crate with
378            // overflow-checks disabled. Since we successfully incremented `self.start`
379            // above (in many cases this will wrap around to MIN), we now unset
380            // the flag so we don't repeat this process in the next iteration.
381            //
382            // This could also happen if `forward_checked` returned None but
383            // (for whatever reason, not applicable to any std implementors)
384            // `forward` doesn't panic when overflow-checks are enabled. In that
385            // case, this is also the correct behavior.
386            self.exhausted = false;
387        }
388        if intrinsics::overflow_checks() {
389            let Some(n) = Step::forward_checked(self.start.clone(), 1) else {
390                self.exhausted = true;
391                return Some(self.start.clone());
392            };
393            return Some(mem::replace(&mut self.start, n));
394        }
395
396        let n = Step::forward(self.start.clone(), 1);
397        Some(mem::replace(&mut self.start, n))
398    }
399
400    #[inline]
401    fn size_hint(&self) -> (usize, Option<usize>) {
402        (usize::MAX, None)
403    }
404
405    #[inline]
406    #[rustc_inherit_overflow_checks]
407    fn nth(&mut self, n: usize) -> Option<A> {
408        // Typically `forward` will cause an overflow-check panic here,
409        // but unset the exhausted flag to handle the uncommon cases.
410        // See the comments in `next` for more details.
411        if self.exhausted {
412            self.start = Step::forward(self.start.clone(), 1);
413            self.exhausted = false;
414        }
415        if intrinsics::overflow_checks() {
416            let plus_n = Step::forward(self.start.clone(), n);
417            if let Some(plus_n1) = Step::forward_checked(plus_n.clone(), 1) {
418                self.start = plus_n1;
419            } else {
420                self.start = plus_n.clone();
421                self.exhausted = true;
422            }
423            return Some(plus_n);
424        }
425
426        let plus_n = Step::forward(self.start.clone(), n);
427        self.start = Step::forward(plus_n.clone(), 1);
428        Some(plus_n)
429    }
430}
431
432#[unstable(feature = "trusted_len", issue = "37572")]
433unsafe impl<A: TrustedStep> TrustedLen for RangeFromIter<A> {}
434
435#[stable(feature = "new_range_from_api", since = "CURRENT_RUSTC_VERSION")]
436impl<A: Step> FusedIterator for RangeFromIter<A> {}
437
438#[stable(feature = "new_range_from_api", since = "CURRENT_RUSTC_VERSION")]
439impl<A: Step> IntoIterator for RangeFrom<A> {
440    type Item = A;
441    type IntoIter = RangeFromIter<A>;
442
443    fn into_iter(self) -> Self::IntoIter {
444        RangeFromIter { start: self.start, exhausted: false }
445    }
446}