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_api", issue = "125687")]
15    /// Returns the remainder of the range being iterated over.
16    pub fn remainder(self) -> Range<A> {
17        Range { start: self.0.start, end: self.0.end }
18    }
19}
20
21/// Safety: This macro must only be used on types that are `Copy` and result in ranges
22/// which have an exact `size_hint()` where the upper bound must not be `None`.
23macro_rules! unsafe_range_trusted_random_access_impl {
24    ($($t:ty)*) => ($(
25        #[doc(hidden)]
26        #[unstable(feature = "trusted_random_access", issue = "none")]
27        unsafe impl TrustedRandomAccess for RangeIter<$t> {}
28
29        #[doc(hidden)]
30        #[unstable(feature = "trusted_random_access", issue = "none")]
31        unsafe impl TrustedRandomAccessNoCoerce for RangeIter<$t> {
32            const MAY_HAVE_SIDE_EFFECT: bool = false;
33        }
34    )*)
35}
36
37unsafe_range_trusted_random_access_impl! {
38    usize u8 u16
39    isize i8 i16
40}
41
42#[cfg(target_pointer_width = "32")]
43unsafe_range_trusted_random_access_impl! {
44    u32 i32
45}
46
47#[cfg(target_pointer_width = "64")]
48unsafe_range_trusted_random_access_impl! {
49    u32 i32
50    u64 i64
51}
52
53#[unstable(feature = "new_range_api", issue = "125687")]
54impl<A: Step> Iterator for RangeIter<A> {
55    type Item = A;
56
57    #[inline]
58    fn next(&mut self) -> Option<A> {
59        self.0.next()
60    }
61
62    #[inline]
63    fn size_hint(&self) -> (usize, Option<usize>) {
64        self.0.size_hint()
65    }
66
67    #[inline]
68    fn count(self) -> usize {
69        self.0.count()
70    }
71
72    #[inline]
73    fn nth(&mut self, n: usize) -> Option<A> {
74        self.0.nth(n)
75    }
76
77    #[inline]
78    fn last(self) -> Option<A> {
79        self.0.last()
80    }
81
82    #[inline]
83    fn min(self) -> Option<A>
84    where
85        A: Ord,
86    {
87        self.0.min()
88    }
89
90    #[inline]
91    fn max(self) -> Option<A>
92    where
93        A: Ord,
94    {
95        self.0.max()
96    }
97
98    #[inline]
99    fn is_sorted(self) -> bool {
100        true
101    }
102
103    #[inline]
104    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
105        self.0.advance_by(n)
106    }
107
108    #[inline]
109    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item
110    where
111        Self: TrustedRandomAccessNoCoerce,
112    {
113        // SAFETY: The TrustedRandomAccess contract requires that callers only pass an index
114        // that is in bounds.
115        // Additionally Self: TrustedRandomAccess is only implemented for Copy types
116        // which means even repeated reads of the same index would be safe.
117        unsafe { Step::forward_unchecked(self.0.start.clone(), idx) }
118    }
119}
120
121#[unstable(feature = "new_range_api", issue = "125687")]
122impl<A: Step> DoubleEndedIterator for RangeIter<A> {
123    #[inline]
124    fn next_back(&mut self) -> Option<A> {
125        self.0.next_back()
126    }
127
128    #[inline]
129    fn nth_back(&mut self, n: usize) -> Option<A> {
130        self.0.nth_back(n)
131    }
132
133    #[inline]
134    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
135        self.0.advance_back_by(n)
136    }
137}
138
139#[unstable(feature = "trusted_len", issue = "37572")]
140unsafe impl<A: TrustedStep> TrustedLen for RangeIter<A> {}
141
142#[unstable(feature = "new_range_api", issue = "125687")]
143impl<A: Step> FusedIterator for RangeIter<A> {}
144
145#[unstable(feature = "new_range_api", issue = "125687")]
146impl<A: Step> IntoIterator for Range<A> {
147    type Item = A;
148    type IntoIter = RangeIter<A>;
149
150    fn into_iter(self) -> Self::IntoIter {
151        RangeIter(self.into())
152    }
153}
154
155/// By-value [`RangeInclusive`] iterator.
156#[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
157#[derive(Debug, Clone)]
158pub struct RangeInclusiveIter<A>(legacy::RangeInclusive<A>);
159
160impl<A: Step> RangeInclusiveIter<A> {
161    /// Returns the remainder of the range being iterated over.
162    ///
163    /// If the iterator is exhausted or empty, returns `None`.
164    #[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
165    pub fn remainder(self) -> Option<RangeInclusive<A>> {
166        if self.0.is_empty() {
167            return None;
168        }
169
170        Some(RangeInclusive { start: self.0.start, last: self.0.end })
171    }
172}
173
174#[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
175impl<A: Step> Iterator for RangeInclusiveIter<A> {
176    type Item = A;
177
178    #[inline]
179    fn next(&mut self) -> Option<A> {
180        self.0.next()
181    }
182
183    #[inline]
184    fn size_hint(&self) -> (usize, Option<usize>) {
185        self.0.size_hint()
186    }
187
188    #[inline]
189    fn count(self) -> usize {
190        self.0.count()
191    }
192
193    #[inline]
194    fn nth(&mut self, n: usize) -> Option<A> {
195        self.0.nth(n)
196    }
197
198    #[inline]
199    fn last(self) -> Option<A> {
200        self.0.last()
201    }
202
203    #[inline]
204    fn min(self) -> Option<A>
205    where
206        A: Ord,
207    {
208        self.0.min()
209    }
210
211    #[inline]
212    fn max(self) -> Option<A>
213    where
214        A: Ord,
215    {
216        self.0.max()
217    }
218
219    #[inline]
220    fn is_sorted(self) -> bool {
221        true
222    }
223
224    #[inline]
225    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
226        self.0.advance_by(n)
227    }
228}
229
230#[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
231impl<A: Step> DoubleEndedIterator for RangeInclusiveIter<A> {
232    #[inline]
233    fn next_back(&mut self) -> Option<A> {
234        self.0.next_back()
235    }
236
237    #[inline]
238    fn nth_back(&mut self, n: usize) -> Option<A> {
239        self.0.nth_back(n)
240    }
241
242    #[inline]
243    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
244        self.0.advance_back_by(n)
245    }
246}
247
248#[unstable(feature = "trusted_len", issue = "37572")]
249unsafe impl<A: TrustedStep> TrustedLen for RangeInclusiveIter<A> {}
250
251#[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
252impl<A: Step> FusedIterator for RangeInclusiveIter<A> {}
253
254#[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
255impl<A: Step> IntoIterator for RangeInclusive<A> {
256    type Item = A;
257    type IntoIter = RangeInclusiveIter<A>;
258
259    fn into_iter(self) -> Self::IntoIter {
260        RangeInclusiveIter(self.into())
261    }
262}
263
264// These macros generate `ExactSizeIterator` impls for various range types.
265//
266// * `ExactSizeIterator::len` is required to always return an exact `usize`,
267//   so no range can be longer than `usize::MAX`.
268// * For integer types in `Range<_>` this is the case for types narrower than or as wide as `usize`.
269//   For integer types in `RangeInclusive<_>`
270//   this is the case for types *strictly narrower* than `usize`
271//   since e.g. `(0..=u64::MAX).len()` would be `u64::MAX + 1`.
272macro_rules! range_exact_iter_impl {
273    ($($t:ty)*) => ($(
274        #[unstable(feature = "new_range_api", issue = "125687")]
275        impl ExactSizeIterator for RangeIter<$t> { }
276    )*)
277}
278
279macro_rules! range_incl_exact_iter_impl {
280    ($($t:ty)*) => ($(
281        #[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
282        impl ExactSizeIterator for RangeInclusiveIter<$t> { }
283    )*)
284}
285
286range_exact_iter_impl! {
287    usize u8 u16
288    isize i8 i16
289}
290
291range_incl_exact_iter_impl! {
292    u8
293    i8
294}
295
296/// By-value [`RangeFrom`] iterator.
297#[unstable(feature = "new_range_api", issue = "125687")]
298#[derive(Debug, Clone)]
299pub struct RangeFromIter<A> {
300    start: A,
301    /// Whether the first element of the iterator has yielded.
302    /// Only used when overflow checks are enabled.
303    first: bool,
304}
305
306impl<A: Step> RangeFromIter<A> {
307    /// Returns the remainder of the range being iterated over.
308    #[inline]
309    #[rustc_inherit_overflow_checks]
310    #[unstable(feature = "new_range_api", issue = "125687")]
311    pub fn remainder(self) -> RangeFrom<A> {
312        if intrinsics::overflow_checks() {
313            if !self.first {
314                return RangeFrom { start: Step::forward(self.start, 1) };
315            }
316        }
317
318        RangeFrom { start: self.start }
319    }
320}
321
322#[unstable(feature = "new_range_api", issue = "125687")]
323impl<A: Step> Iterator for RangeFromIter<A> {
324    type Item = A;
325
326    #[inline]
327    #[rustc_inherit_overflow_checks]
328    fn next(&mut self) -> Option<A> {
329        if intrinsics::overflow_checks() {
330            if self.first {
331                self.first = false;
332                return Some(self.start.clone());
333            }
334
335            self.start = Step::forward(self.start.clone(), 1);
336            return Some(self.start.clone());
337        }
338
339        let n = Step::forward(self.start.clone(), 1);
340        Some(mem::replace(&mut self.start, n))
341    }
342
343    #[inline]
344    fn size_hint(&self) -> (usize, Option<usize>) {
345        (usize::MAX, None)
346    }
347
348    #[inline]
349    #[rustc_inherit_overflow_checks]
350    fn nth(&mut self, n: usize) -> Option<A> {
351        if intrinsics::overflow_checks() {
352            if self.first {
353                self.first = false;
354
355                let plus_n = Step::forward(self.start.clone(), n);
356                self.start = plus_n.clone();
357                return Some(plus_n);
358            }
359
360            let plus_n = Step::forward(self.start.clone(), n);
361            self.start = Step::forward(plus_n.clone(), 1);
362            return Some(self.start.clone());
363        }
364
365        let plus_n = Step::forward(self.start.clone(), n);
366        self.start = Step::forward(plus_n.clone(), 1);
367        Some(plus_n)
368    }
369}
370
371#[unstable(feature = "trusted_len", issue = "37572")]
372unsafe impl<A: TrustedStep> TrustedLen for RangeFromIter<A> {}
373
374#[unstable(feature = "new_range_api", issue = "125687")]
375impl<A: Step> FusedIterator for RangeFromIter<A> {}
376
377#[unstable(feature = "new_range_api", issue = "125687")]
378impl<A: Step> IntoIterator for RangeFrom<A> {
379    type Item = A;
380    type IntoIter = RangeFromIter<A>;
381
382    fn into_iter(self) -> Self::IntoIter {
383        RangeFromIter { start: self.start, first: true }
384    }
385}