core/
range.rs

1//! # Experimental replacement range types
2//!
3//! The types within this module are meant to replace the existing
4//! `Range`, `RangeInclusive`, and `RangeFrom` types in a future edition.
5//!
6//! ```
7//! #![feature(new_range_api)]
8//! use core::range::{Range, RangeFrom, RangeInclusive};
9//!
10//! let arr = [0, 1, 2, 3, 4];
11//! assert_eq!(arr[                      ..   ], [0, 1, 2, 3, 4]);
12//! assert_eq!(arr[                      .. 3 ], [0, 1, 2      ]);
13//! assert_eq!(arr[                      ..=3 ], [0, 1, 2, 3   ]);
14//! assert_eq!(arr[     RangeFrom::from(1..  )], [   1, 2, 3, 4]);
15//! assert_eq!(arr[         Range::from(1..3 )], [   1, 2      ]);
16//! assert_eq!(arr[RangeInclusive::from(1..=3)], [   1, 2, 3   ]);
17//! ```
18
19use crate::fmt;
20use crate::hash::Hash;
21
22mod iter;
23
24#[unstable(feature = "new_range_api", issue = "125687")]
25pub mod legacy;
26
27use Bound::{Excluded, Included, Unbounded};
28#[doc(inline)]
29pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive};
30
31#[doc(inline)]
32pub use crate::iter::Step;
33#[doc(inline)]
34pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive};
35
36/// A (half-open) range bounded inclusively below and exclusively above
37/// (`start..end` in a future edition).
38///
39/// The range `start..end` contains all values with `start <= x < end`.
40/// It is empty if `start >= end`.
41///
42/// # Examples
43///
44/// ```
45/// #![feature(new_range_api)]
46/// use core::range::Range;
47///
48/// assert_eq!(Range::from(3..5), Range { start: 3, end: 5 });
49/// assert_eq!(3 + 4 + 5, Range::from(3..6).into_iter().sum());
50/// ```
51#[cfg_attr(not(bootstrap), lang = "RangeCopy")]
52#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
53#[unstable(feature = "new_range_api", issue = "125687")]
54pub struct Range<Idx> {
55    /// The lower bound of the range (inclusive).
56    #[unstable(feature = "new_range_api", issue = "125687")]
57    pub start: Idx,
58    /// The upper bound of the range (exclusive).
59    #[unstable(feature = "new_range_api", issue = "125687")]
60    pub end: Idx,
61}
62
63#[unstable(feature = "new_range_api", issue = "125687")]
64impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
65    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
66        self.start.fmt(fmt)?;
67        write!(fmt, "..")?;
68        self.end.fmt(fmt)?;
69        Ok(())
70    }
71}
72
73impl<Idx: Step> Range<Idx> {
74    /// Creates an iterator over the elements within this range.
75    ///
76    /// Shorthand for `.clone().into_iter()`
77    ///
78    /// # Examples
79    ///
80    /// ```
81    /// #![feature(new_range_api)]
82    /// use core::range::Range;
83    ///
84    /// let mut i = Range::from(3..9).iter().map(|n| n*n);
85    /// assert_eq!(i.next(), Some(9));
86    /// assert_eq!(i.next(), Some(16));
87    /// assert_eq!(i.next(), Some(25));
88    /// ```
89    #[unstable(feature = "new_range_api", issue = "125687")]
90    #[inline]
91    pub fn iter(&self) -> IterRange<Idx> {
92        self.clone().into_iter()
93    }
94}
95
96impl<Idx: PartialOrd<Idx>> Range<Idx> {
97    /// Returns `true` if `item` is contained in the range.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// #![feature(new_range_api)]
103    /// use core::range::Range;
104    ///
105    /// assert!(!Range::from(3..5).contains(&2));
106    /// assert!( Range::from(3..5).contains(&3));
107    /// assert!( Range::from(3..5).contains(&4));
108    /// assert!(!Range::from(3..5).contains(&5));
109    ///
110    /// assert!(!Range::from(3..3).contains(&3));
111    /// assert!(!Range::from(3..2).contains(&3));
112    ///
113    /// assert!( Range::from(0.0..1.0).contains(&0.5));
114    /// assert!(!Range::from(0.0..1.0).contains(&f32::NAN));
115    /// assert!(!Range::from(0.0..f32::NAN).contains(&0.5));
116    /// assert!(!Range::from(f32::NAN..1.0).contains(&0.5));
117    /// ```
118    #[inline]
119    #[unstable(feature = "new_range_api", issue = "125687")]
120    pub fn contains<U>(&self, item: &U) -> bool
121    where
122        Idx: PartialOrd<U>,
123        U: ?Sized + PartialOrd<Idx>,
124    {
125        <Self as RangeBounds<Idx>>::contains(self, item)
126    }
127
128    /// Returns `true` if the range contains no items.
129    ///
130    /// # Examples
131    ///
132    /// ```
133    /// #![feature(new_range_api)]
134    /// use core::range::Range;
135    ///
136    /// assert!(!Range::from(3..5).is_empty());
137    /// assert!( Range::from(3..3).is_empty());
138    /// assert!( Range::from(3..2).is_empty());
139    /// ```
140    ///
141    /// The range is empty if either side is incomparable:
142    ///
143    /// ```
144    /// #![feature(new_range_api)]
145    /// use core::range::Range;
146    ///
147    /// assert!(!Range::from(3.0..5.0).is_empty());
148    /// assert!( Range::from(3.0..f32::NAN).is_empty());
149    /// assert!( Range::from(f32::NAN..5.0).is_empty());
150    /// ```
151    #[inline]
152    #[unstable(feature = "new_range_api", issue = "125687")]
153    pub fn is_empty(&self) -> bool {
154        !(self.start < self.end)
155    }
156}
157
158#[unstable(feature = "new_range_api", issue = "125687")]
159impl<T> RangeBounds<T> for Range<T> {
160    fn start_bound(&self) -> Bound<&T> {
161        Included(&self.start)
162    }
163    fn end_bound(&self) -> Bound<&T> {
164        Excluded(&self.end)
165    }
166}
167
168#[unstable(feature = "new_range_api", issue = "125687")]
169impl<T> RangeBounds<T> for Range<&T> {
170    fn start_bound(&self) -> Bound<&T> {
171        Included(self.start)
172    }
173    fn end_bound(&self) -> Bound<&T> {
174        Excluded(self.end)
175    }
176}
177
178#[unstable(feature = "new_range_api", issue = "125687")]
179impl<T> From<Range<T>> for legacy::Range<T> {
180    #[inline]
181    fn from(value: Range<T>) -> Self {
182        Self { start: value.start, end: value.end }
183    }
184}
185#[unstable(feature = "new_range_api", issue = "125687")]
186impl<T> From<legacy::Range<T>> for Range<T> {
187    #[inline]
188    fn from(value: legacy::Range<T>) -> Self {
189        Self { start: value.start, end: value.end }
190    }
191}
192
193/// A range bounded inclusively below and above (`start..=end`).
194///
195/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
196/// and `x <= end`. It is empty unless `start <= end`.
197///
198/// # Examples
199///
200/// The `start..=end` syntax is a `RangeInclusive`:
201///
202/// ```
203/// #![feature(new_range_api)]
204/// use core::range::RangeInclusive;
205///
206/// assert_eq!(RangeInclusive::from(3..=5), RangeInclusive { start: 3, end: 5 });
207/// assert_eq!(3 + 4 + 5, RangeInclusive::from(3..=5).into_iter().sum());
208/// ```
209#[cfg_attr(not(bootstrap), lang = "RangeInclusiveCopy")]
210#[derive(Clone, Copy, PartialEq, Eq, Hash)]
211#[unstable(feature = "new_range_api", issue = "125687")]
212pub struct RangeInclusive<Idx> {
213    /// The lower bound of the range (inclusive).
214    #[unstable(feature = "new_range_api", issue = "125687")]
215    pub start: Idx,
216    /// The upper bound of the range (inclusive).
217    #[unstable(feature = "new_range_api", issue = "125687")]
218    pub end: Idx,
219}
220
221#[unstable(feature = "new_range_api", issue = "125687")]
222impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
223    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
224        self.start.fmt(fmt)?;
225        write!(fmt, "..=")?;
226        self.end.fmt(fmt)?;
227        Ok(())
228    }
229}
230
231impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
232    /// Returns `true` if `item` is contained in the range.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// #![feature(new_range_api)]
238    /// use core::range::RangeInclusive;
239    ///
240    /// assert!(!RangeInclusive::from(3..=5).contains(&2));
241    /// assert!( RangeInclusive::from(3..=5).contains(&3));
242    /// assert!( RangeInclusive::from(3..=5).contains(&4));
243    /// assert!( RangeInclusive::from(3..=5).contains(&5));
244    /// assert!(!RangeInclusive::from(3..=5).contains(&6));
245    ///
246    /// assert!( RangeInclusive::from(3..=3).contains(&3));
247    /// assert!(!RangeInclusive::from(3..=2).contains(&3));
248    ///
249    /// assert!( RangeInclusive::from(0.0..=1.0).contains(&1.0));
250    /// assert!(!RangeInclusive::from(0.0..=1.0).contains(&f32::NAN));
251    /// assert!(!RangeInclusive::from(0.0..=f32::NAN).contains(&0.0));
252    /// assert!(!RangeInclusive::from(f32::NAN..=1.0).contains(&1.0));
253    /// ```
254    #[inline]
255    #[unstable(feature = "new_range_api", issue = "125687")]
256    pub fn contains<U>(&self, item: &U) -> bool
257    where
258        Idx: PartialOrd<U>,
259        U: ?Sized + PartialOrd<Idx>,
260    {
261        <Self as RangeBounds<Idx>>::contains(self, item)
262    }
263
264    /// Returns `true` if the range contains no items.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// #![feature(new_range_api)]
270    /// use core::range::RangeInclusive;
271    ///
272    /// assert!(!RangeInclusive::from(3..=5).is_empty());
273    /// assert!(!RangeInclusive::from(3..=3).is_empty());
274    /// assert!( RangeInclusive::from(3..=2).is_empty());
275    /// ```
276    ///
277    /// The range is empty if either side is incomparable:
278    ///
279    /// ```
280    /// #![feature(new_range_api)]
281    /// use core::range::RangeInclusive;
282    ///
283    /// assert!(!RangeInclusive::from(3.0..=5.0).is_empty());
284    /// assert!( RangeInclusive::from(3.0..=f32::NAN).is_empty());
285    /// assert!( RangeInclusive::from(f32::NAN..=5.0).is_empty());
286    /// ```
287    #[unstable(feature = "new_range_api", issue = "125687")]
288    #[inline]
289    pub fn is_empty(&self) -> bool {
290        !(self.start <= self.end)
291    }
292}
293
294impl<Idx: Step> RangeInclusive<Idx> {
295    /// Creates an iterator over the elements within this range.
296    ///
297    /// Shorthand for `.clone().into_iter()`
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// #![feature(new_range_api)]
303    /// use core::range::RangeInclusive;
304    ///
305    /// let mut i = RangeInclusive::from(3..=8).iter().map(|n| n*n);
306    /// assert_eq!(i.next(), Some(9));
307    /// assert_eq!(i.next(), Some(16));
308    /// assert_eq!(i.next(), Some(25));
309    /// ```
310    #[unstable(feature = "new_range_api", issue = "125687")]
311    #[inline]
312    pub fn iter(&self) -> IterRangeInclusive<Idx> {
313        self.clone().into_iter()
314    }
315}
316
317impl RangeInclusive<usize> {
318    /// Converts to an exclusive `Range` for `SliceIndex` implementations.
319    /// The caller is responsible for dealing with `end == usize::MAX`.
320    #[inline]
321    pub(crate) const fn into_slice_range(self) -> Range<usize> {
322        Range { start: self.start, end: self.end + 1 }
323    }
324}
325
326#[unstable(feature = "new_range_api", issue = "125687")]
327impl<T> RangeBounds<T> for RangeInclusive<T> {
328    fn start_bound(&self) -> Bound<&T> {
329        Included(&self.start)
330    }
331    fn end_bound(&self) -> Bound<&T> {
332        Included(&self.end)
333    }
334}
335
336#[unstable(feature = "new_range_api", issue = "125687")]
337impl<T> RangeBounds<T> for RangeInclusive<&T> {
338    fn start_bound(&self) -> Bound<&T> {
339        Included(self.start)
340    }
341    fn end_bound(&self) -> Bound<&T> {
342        Included(self.end)
343    }
344}
345
346#[unstable(feature = "new_range_api", issue = "125687")]
347impl<T> From<RangeInclusive<T>> for legacy::RangeInclusive<T> {
348    #[inline]
349    fn from(value: RangeInclusive<T>) -> Self {
350        Self::new(value.start, value.end)
351    }
352}
353#[unstable(feature = "new_range_api", issue = "125687")]
354impl<T> From<legacy::RangeInclusive<T>> for RangeInclusive<T> {
355    #[inline]
356    fn from(value: legacy::RangeInclusive<T>) -> Self {
357        assert!(
358            !value.exhausted,
359            "attempted to convert from an exhausted `legacy::RangeInclusive` (unspecified behavior)"
360        );
361
362        let (start, end) = value.into_inner();
363        RangeInclusive { start, end }
364    }
365}
366
367/// A range only bounded inclusively below (`start..`).
368///
369/// The `RangeFrom` `start..` contains all values with `x >= start`.
370///
371/// *Note*: Overflow in the [`Iterator`] implementation (when the contained
372/// data type reaches its numerical limit) is allowed to panic, wrap, or
373/// saturate. This behavior is defined by the implementation of the [`Step`]
374/// trait. For primitive integers, this follows the normal rules, and respects
375/// the overflow checks profile (panic in debug, wrap in release). Note also
376/// that overflow happens earlier than you might assume: the overflow happens
377/// in the call to `next` that yields the maximum value, as the range must be
378/// set to a state to yield the next value.
379///
380/// [`Step`]: crate::iter::Step
381///
382/// # Examples
383///
384/// The `start..` syntax is a `RangeFrom`:
385///
386/// ```
387/// #![feature(new_range_api)]
388/// use core::range::RangeFrom;
389///
390/// assert_eq!(RangeFrom::from(2..), core::range::RangeFrom { start: 2 });
391/// assert_eq!(2 + 3 + 4, RangeFrom::from(2..).into_iter().take(3).sum());
392/// ```
393#[cfg_attr(not(bootstrap), lang = "RangeFromCopy")]
394#[derive(Clone, Copy, PartialEq, Eq, Hash)]
395#[unstable(feature = "new_range_api", issue = "125687")]
396pub struct RangeFrom<Idx> {
397    /// The lower bound of the range (inclusive).
398    #[unstable(feature = "new_range_api", issue = "125687")]
399    pub start: Idx,
400}
401
402#[unstable(feature = "new_range_api", issue = "125687")]
403impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
404    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
405        self.start.fmt(fmt)?;
406        write!(fmt, "..")?;
407        Ok(())
408    }
409}
410
411impl<Idx: Step> RangeFrom<Idx> {
412    /// Creates an iterator over the elements within this range.
413    ///
414    /// Shorthand for `.clone().into_iter()`
415    ///
416    /// # Examples
417    ///
418    /// ```
419    /// #![feature(new_range_api)]
420    /// use core::range::RangeFrom;
421    ///
422    /// let mut i = RangeFrom::from(3..).iter().map(|n| n*n);
423    /// assert_eq!(i.next(), Some(9));
424    /// assert_eq!(i.next(), Some(16));
425    /// assert_eq!(i.next(), Some(25));
426    /// ```
427    #[unstable(feature = "new_range_api", issue = "125687")]
428    #[inline]
429    pub fn iter(&self) -> IterRangeFrom<Idx> {
430        self.clone().into_iter()
431    }
432}
433
434impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
435    /// Returns `true` if `item` is contained in the range.
436    ///
437    /// # Examples
438    ///
439    /// ```
440    /// #![feature(new_range_api)]
441    /// use core::range::RangeFrom;
442    ///
443    /// assert!(!RangeFrom::from(3..).contains(&2));
444    /// assert!( RangeFrom::from(3..).contains(&3));
445    /// assert!( RangeFrom::from(3..).contains(&1_000_000_000));
446    ///
447    /// assert!( RangeFrom::from(0.0..).contains(&0.5));
448    /// assert!(!RangeFrom::from(0.0..).contains(&f32::NAN));
449    /// assert!(!RangeFrom::from(f32::NAN..).contains(&0.5));
450    /// ```
451    #[inline]
452    #[unstable(feature = "new_range_api", issue = "125687")]
453    pub fn contains<U>(&self, item: &U) -> bool
454    where
455        Idx: PartialOrd<U>,
456        U: ?Sized + PartialOrd<Idx>,
457    {
458        <Self as RangeBounds<Idx>>::contains(self, item)
459    }
460}
461
462#[unstable(feature = "new_range_api", issue = "125687")]
463impl<T> RangeBounds<T> for RangeFrom<T> {
464    fn start_bound(&self) -> Bound<&T> {
465        Included(&self.start)
466    }
467    fn end_bound(&self) -> Bound<&T> {
468        Unbounded
469    }
470}
471
472#[unstable(feature = "new_range_api", issue = "125687")]
473impl<T> RangeBounds<T> for RangeFrom<&T> {
474    fn start_bound(&self) -> Bound<&T> {
475        Included(self.start)
476    }
477    fn end_bound(&self) -> Bound<&T> {
478        Unbounded
479    }
480}
481
482#[unstable(feature = "new_range_api", issue = "125687")]
483impl<T> From<RangeFrom<T>> for legacy::RangeFrom<T> {
484    #[inline]
485    fn from(value: RangeFrom<T>) -> Self {
486        Self { start: value.start }
487    }
488}
489#[unstable(feature = "new_range_api", issue = "125687")]
490impl<T> From<legacy::RangeFrom<T>> for RangeFrom<T> {
491    #[inline]
492    fn from(value: legacy::RangeFrom<T>) -> Self {
493        Self { start: value.start }
494    }
495}