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