Skip to main content

core/ops/
range.rs

1use crate::fmt;
2use crate::hash::Hash;
3use crate::marker::Destruct;
4/// An unbounded range (`..`).
5///
6/// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`.
7/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
8///
9/// # Examples
10///
11/// The `..` syntax is a `RangeFull`:
12///
13/// ```
14/// assert_eq!(.., std::ops::RangeFull);
15/// ```
16///
17/// It does not have an [`IntoIterator`] implementation, so you can't use it in
18/// a `for` loop directly. This won't compile:
19///
20/// ```compile_fail,E0277
21/// for i in .. {
22///     // ...
23/// }
24/// ```
25///
26/// Used as a [slicing index], `RangeFull` produces the full array as a slice.
27///
28/// ```
29/// let arr = [0, 1, 2, 3, 4];
30/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]); // This is the `RangeFull`
31/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
32/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
33/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
34/// assert_eq!(arr[1.. 3], [   1, 2      ]);
35/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
36/// ```
37///
38/// [slicing index]: crate::slice::SliceIndex
39#[lang = "RangeFull"]
40#[doc(alias = "..")]
41#[derive(Copy, Hash)]
42#[derive_const(Clone, Default, PartialEq, Eq)]
43#[stable(feature = "rust1", since = "1.0.0")]
44#[ferrocene::prevalidated]
45pub struct RangeFull;
46
47#[stable(feature = "rust1", since = "1.0.0")]
48impl fmt::Debug for RangeFull {
49    #[ferrocene::prevalidated]
50    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(fmt, "..")
52    }
53}
54
55/// A (half-open) range bounded inclusively below and exclusively above
56/// (`start..end`).
57///
58/// The range `start..end` contains all values with `start <= x < end`.
59/// It is empty if `start >= end`.
60///
61/// Note that this type is not suited to represent all possible ranges. For example, `Range<u8>`
62/// cannot represent the range that covers all of `u8`. Use [`(Bound<T>, Bound<T>)`][Bound] if you
63/// need a type that can store an arbitrary range.
64///
65/// # Examples
66///
67/// The `start..end` syntax is a `Range`:
68///
69/// ```
70/// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
71/// assert_eq!(3 + 4 + 5, (3..6).sum());
72/// ```
73///
74/// ```
75/// let arr = [0, 1, 2, 3, 4];
76/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
77/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
78/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
79/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
80/// assert_eq!(arr[1.. 3], [   1, 2      ]); // This is a `Range`
81/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
82/// ```
83#[lang = "Range"]
84#[doc(alias = "..")]
85#[derive(Eq, Hash)]
86#[derive_const(Clone, Default, PartialEq)] // not Copy -- see #27186
87#[stable(feature = "rust1", since = "1.0.0")]
88#[ferrocene::prevalidated]
89pub struct Range<Idx> {
90    /// The lower bound of the range (inclusive).
91    #[stable(feature = "rust1", since = "1.0.0")]
92    pub start: Idx,
93    /// The upper bound of the range (exclusive).
94    #[stable(feature = "rust1", since = "1.0.0")]
95    pub end: Idx,
96}
97
98#[stable(feature = "rust1", since = "1.0.0")]
99impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
100    #[ferrocene::prevalidated]
101    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
102        self.start.fmt(fmt)?;
103        write!(fmt, "..")?;
104        self.end.fmt(fmt)?;
105        Ok(())
106    }
107}
108
109impl<Idx: PartialOrd<Idx>> Range<Idx> {
110    /// Returns `true` if `item` is contained in the range.
111    ///
112    /// # Examples
113    ///
114    /// ```
115    /// assert!(!(3..5).contains(&2));
116    /// assert!( (3..5).contains(&3));
117    /// assert!( (3..5).contains(&4));
118    /// assert!(!(3..5).contains(&5));
119    ///
120    /// assert!(!(3..3).contains(&3));
121    /// assert!(!(3..2).contains(&3));
122    ///
123    /// assert!( (0.0..1.0).contains(&0.5));
124    /// assert!(!(0.0..1.0).contains(&f32::NAN));
125    /// assert!(!(0.0..f32::NAN).contains(&0.5));
126    /// assert!(!(f32::NAN..1.0).contains(&0.5));
127    /// ```
128    #[inline]
129    #[stable(feature = "range_contains", since = "1.35.0")]
130    #[rustc_const_unstable(feature = "const_range", issue = "none")]
131    #[ferrocene::prevalidated]
132    pub const fn contains<U>(&self, item: &U) -> bool
133    where
134        Idx: [const] PartialOrd<U>,
135        U: ?Sized + [const] PartialOrd<Idx>,
136    {
137        <Self as RangeBounds<Idx>>::contains(self, item)
138    }
139
140    /// Returns `true` if the range contains no items.
141    ///
142    /// # Examples
143    ///
144    /// ```
145    /// assert!(!(3..5).is_empty());
146    /// assert!( (3..3).is_empty());
147    /// assert!( (3..2).is_empty());
148    /// ```
149    ///
150    /// The range is empty if either side is incomparable:
151    ///
152    /// ```
153    /// assert!(!(3.0..5.0).is_empty());
154    /// assert!( (3.0..f32::NAN).is_empty());
155    /// assert!( (f32::NAN..5.0).is_empty());
156    /// ```
157    #[ferrocene::prevalidated]
158    #[inline]
159    #[stable(feature = "range_is_empty", since = "1.47.0")]
160    #[rustc_const_unstable(feature = "const_range", issue = "none")]
161    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")]
162    pub const fn is_empty(&self) -> bool
163    where
164        Idx: [const] PartialOrd<Idx>,
165    {
166        !(self.start < self.end)
167    }
168}
169
170/// A range only bounded inclusively below (`start..`).
171///
172/// The `RangeFrom` `start..` contains all values with `x >= start`.
173///
174/// *Note*: Overflow in the [`Iterator`] implementation (when the contained
175/// data type reaches its numerical limit) is allowed to panic, wrap, or
176/// saturate. This behavior is defined by the implementation of the [`Step`]
177/// trait. For primitive integers, this follows the normal rules, and respects
178/// the overflow checks profile (panic in debug, wrap in release). Note also
179/// that overflow happens earlier than you might assume: the overflow happens
180/// in the call to `next` that yields the maximum value, as the range must be
181/// set to a state to yield the next value.
182///
183/// [`Step`]: crate::iter::Step
184///
185/// # Examples
186///
187/// The `start..` syntax is a `RangeFrom`:
188///
189/// ```
190/// assert_eq!((2..), std::ops::RangeFrom { start: 2 });
191/// assert_eq!(2 + 3 + 4, (2..).take(3).sum());
192/// ```
193///
194/// ```
195/// let arr = [0, 1, 2, 3, 4];
196/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
197/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
198/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
199/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]); // This is a `RangeFrom`
200/// assert_eq!(arr[1.. 3], [   1, 2      ]);
201/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
202/// ```
203#[lang = "RangeFrom"]
204#[doc(alias = "..")]
205#[derive(Eq, Hash)]
206#[derive_const(Clone, PartialEq)] // not Copy -- see #27186
207#[stable(feature = "rust1", since = "1.0.0")]
208#[ferrocene::prevalidated]
209pub struct RangeFrom<Idx> {
210    /// The lower bound of the range (inclusive).
211    #[stable(feature = "rust1", since = "1.0.0")]
212    pub start: Idx,
213}
214
215#[stable(feature = "rust1", since = "1.0.0")]
216impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
217    #[ferrocene::prevalidated]
218    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
219        self.start.fmt(fmt)?;
220        write!(fmt, "..")?;
221        Ok(())
222    }
223}
224
225impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
226    /// Returns `true` if `item` is contained in the range.
227    ///
228    /// # Examples
229    ///
230    /// ```
231    /// assert!(!(3..).contains(&2));
232    /// assert!( (3..).contains(&3));
233    /// assert!( (3..).contains(&1_000_000_000));
234    ///
235    /// assert!( (0.0..).contains(&0.5));
236    /// assert!(!(0.0..).contains(&f32::NAN));
237    /// assert!(!(f32::NAN..).contains(&0.5));
238    /// ```
239    #[inline]
240    #[stable(feature = "range_contains", since = "1.35.0")]
241    #[rustc_const_unstable(feature = "const_range", issue = "none")]
242    pub const fn contains<U>(&self, item: &U) -> bool
243    where
244        Idx: [const] PartialOrd<U>,
245        U: ?Sized + [const] PartialOrd<Idx>,
246    {
247        <Self as RangeBounds<Idx>>::contains(self, item)
248    }
249}
250
251/// A range only bounded exclusively above (`..end`).
252///
253/// The `RangeTo` `..end` contains all values with `x < end`.
254/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
255///
256/// # Examples
257///
258/// The `..end` syntax is a `RangeTo`:
259///
260/// ```
261/// assert_eq!((..5), std::ops::RangeTo { end: 5 });
262/// ```
263///
264/// It does not have an [`IntoIterator`] implementation, so you can't use it in
265/// a `for` loop directly. This won't compile:
266///
267/// ```compile_fail,E0277
268/// // error[E0277]: the trait bound `std::ops::RangeTo<{integer}>:
269/// // std::iter::Iterator` is not satisfied
270/// for i in ..5 {
271///     // ...
272/// }
273/// ```
274///
275/// When used as a [slicing index], `RangeTo` produces a slice of all array
276/// elements before the index indicated by `end`.
277///
278/// ```
279/// let arr = [0, 1, 2, 3, 4];
280/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
281/// assert_eq!(arr[ .. 3], [0, 1, 2      ]); // This is a `RangeTo`
282/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
283/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
284/// assert_eq!(arr[1.. 3], [   1, 2      ]);
285/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
286/// ```
287///
288/// [slicing index]: crate::slice::SliceIndex
289#[lang = "RangeTo"]
290#[doc(alias = "..")]
291#[derive(Copy, Eq, Hash)]
292#[derive_const(Clone, PartialEq)]
293#[stable(feature = "rust1", since = "1.0.0")]
294#[ferrocene::prevalidated]
295pub struct RangeTo<Idx> {
296    /// The upper bound of the range (exclusive).
297    #[stable(feature = "rust1", since = "1.0.0")]
298    pub end: Idx,
299}
300
301#[stable(feature = "rust1", since = "1.0.0")]
302impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
303    #[ferrocene::prevalidated]
304    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
305        write!(fmt, "..")?;
306        self.end.fmt(fmt)?;
307        Ok(())
308    }
309}
310
311impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
312    /// Returns `true` if `item` is contained in the range.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// assert!( (..5).contains(&-1_000_000_000));
318    /// assert!( (..5).contains(&4));
319    /// assert!(!(..5).contains(&5));
320    ///
321    /// assert!( (..1.0).contains(&0.5));
322    /// assert!(!(..1.0).contains(&f32::NAN));
323    /// assert!(!(..f32::NAN).contains(&0.5));
324    /// ```
325    #[inline]
326    #[stable(feature = "range_contains", since = "1.35.0")]
327    #[rustc_const_unstable(feature = "const_range", issue = "none")]
328    pub const fn contains<U>(&self, item: &U) -> bool
329    where
330        Idx: [const] PartialOrd<U>,
331        U: ?Sized + [const] PartialOrd<Idx>,
332    {
333        <Self as RangeBounds<Idx>>::contains(self, item)
334    }
335}
336
337/// A range bounded inclusively below and above (`start..=end`).
338///
339/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
340/// and `x <= end`. It is empty unless `start <= end`.
341///
342/// This iterator is [fused], but the specific values of `start` and `end` after
343/// iteration has finished are **unspecified** other than that [`.is_empty()`]
344/// will return `true` once no more values will be produced.
345///
346/// [fused]: crate::iter::FusedIterator
347/// [`.is_empty()`]: RangeInclusive::is_empty
348///
349/// # Examples
350///
351/// The `start..=end` syntax is a `RangeInclusive`:
352///
353/// ```
354/// assert_eq!((3..=5), std::ops::RangeInclusive::new(3, 5));
355/// assert_eq!(3 + 4 + 5, (3..=5).sum());
356/// ```
357///
358/// ```
359/// let arr = [0, 1, 2, 3, 4];
360/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
361/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
362/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
363/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
364/// assert_eq!(arr[1.. 3], [   1, 2      ]);
365/// assert_eq!(arr[1..=3], [   1, 2, 3   ]); // This is a `RangeInclusive`
366/// ```
367#[lang = "RangeInclusive"]
368#[doc(alias = "..=")]
369#[derive(Clone, Hash)]
370#[derive_const(Eq, PartialEq)] // not Copy -- see #27186
371#[stable(feature = "inclusive_range", since = "1.26.0")]
372#[ferrocene::prevalidated]
373pub struct RangeInclusive<Idx> {
374    // Note that the fields here are not public to allow changing the
375    // representation in the future; in particular, while we could plausibly
376    // expose start/end, modifying them without changing (future/current)
377    // private fields may lead to incorrect behavior, so we don't want to
378    // support that mode.
379    pub(crate) start: Idx,
380    pub(crate) end: Idx,
381
382    // This field represents an overflow flag for either bound (start or end):
383    //  - `false` upon construction
384    //  - `false` when iteration has yielded an element and
385    //    neither bound has overflowed the valid range of `Idx`
386    //  - `true` when iteration has caused either bound to
387    //    overflow the valid range of `Idx`
388    //
389    // When this is true, `start` or `end` may be left in an unspecified state,
390    // often wrapping (modular arithmetic) around at the boundary of `Idx`.
391    //
392    // This is required to support PartialEq and Hash without a PartialOrd bound or specialization.
393    pub(crate) exhausted: bool,
394}
395
396impl<Idx> RangeInclusive<Idx> {
397    /// Creates a new inclusive range. Equivalent to writing `start..=end`.
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// use std::ops::RangeInclusive;
403    ///
404    /// assert_eq!(3..=5, RangeInclusive::new(3, 5));
405    /// ```
406    #[lang = "range_inclusive_new"]
407    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
408    #[inline]
409    #[rustc_promotable]
410    #[rustc_const_stable(feature = "const_range_new", since = "1.32.0")]
411    #[ferrocene::prevalidated]
412    pub const fn new(start: Idx, end: Idx) -> Self {
413        Self { start, end, exhausted: false }
414    }
415
416    /// Returns the lower bound of the range (inclusive).
417    ///
418    /// When using an inclusive range for iteration, the values of `start()` and
419    /// [`end()`] are unspecified after the iteration ended. To determine
420    /// whether the inclusive range is empty, use the [`is_empty()`] method
421    /// instead of comparing `start() > end()`.
422    ///
423    /// Note: the value returned by this method is unspecified after the range
424    /// has been iterated to exhaustion.
425    ///
426    /// [`end()`]: RangeInclusive::end
427    /// [`is_empty()`]: RangeInclusive::is_empty
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// assert_eq!((3..=5).start(), &3);
433    /// ```
434    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
435    #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
436    #[inline]
437    #[ferrocene::prevalidated]
438    pub const fn start(&self) -> &Idx {
439        &self.start
440    }
441
442    /// Returns the upper bound of the range (inclusive).
443    ///
444    /// When using an inclusive range for iteration, the values of [`start()`]
445    /// and `end()` are unspecified after the iteration ended. To determine
446    /// whether the inclusive range is empty, use the [`is_empty()`] method
447    /// instead of comparing `start() > end()`.
448    ///
449    /// Note: the value returned by this method is unspecified after the range
450    /// has been iterated to exhaustion.
451    ///
452    /// [`start()`]: RangeInclusive::start
453    /// [`is_empty()`]: RangeInclusive::is_empty
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// assert_eq!((3..=5).end(), &5);
459    /// ```
460    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
461    #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
462    #[inline]
463    #[ferrocene::prevalidated]
464    pub const fn end(&self) -> &Idx {
465        &self.end
466    }
467
468    /// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
469    ///
470    /// Note: the value returned by this method is unspecified after the range
471    /// has been iterated to exhaustion.
472    ///
473    /// # Examples
474    ///
475    /// ```
476    /// assert_eq!((3..=5).into_inner(), (3, 5));
477    /// ```
478    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
479    #[inline]
480    #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")]
481    #[ferrocene::prevalidated]
482    pub const fn into_inner(self) -> (Idx, Idx) {
483        (self.start, self.end)
484    }
485}
486
487impl RangeInclusive<usize> {
488    /// Converts to an exclusive `Range` for `SliceIndex` implementations.
489    /// The caller is responsible for dealing with `end == usize::MAX`.
490    #[inline]
491    #[ferrocene::prevalidated]
492    pub(crate) const fn into_slice_range(self) -> Range<usize> {
493        // Typically users should not be indexing with exhausted instances,
494        // but this heuristic should apply to most cases. This doesn't
495        // handle reverse iteration well (`next_back` and `nth_back` can
496        // cause `end` to wrap around to values at or near `usize::MAX`),
497        // but using an exhausted `RangeInclusive` after reverse iteration
498        // is an exceedingly rare case.
499
500        // If we're not exhausted, we want to simply slice `start..end + 1`.
501        // If we are exhausted, then slicing with `end + 1..end + 1` gives us an
502        // empty range that is still subject to bounds-checks for that endpoint.
503        let exclusive_end = self.end + 1;
504        let start = if self.exhausted { exclusive_end } else { self.start };
505        start..exclusive_end
506    }
507}
508
509#[stable(feature = "inclusive_range", since = "1.26.0")]
510impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
511    #[ferrocene::prevalidated]
512    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
513        self.start.fmt(fmt)?;
514        write!(fmt, "..=")?;
515        self.end.fmt(fmt)?;
516        if self.exhausted {
517            write!(fmt, " (exhausted)")?;
518        }
519        Ok(())
520    }
521}
522
523impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
524    /// Returns `true` if `item` is contained in the range.
525    ///
526    /// # Examples
527    ///
528    /// ```
529    /// assert!(!(3..=5).contains(&2));
530    /// assert!( (3..=5).contains(&3));
531    /// assert!( (3..=5).contains(&4));
532    /// assert!( (3..=5).contains(&5));
533    /// assert!(!(3..=5).contains(&6));
534    ///
535    /// assert!( (3..=3).contains(&3));
536    /// assert!(!(3..=2).contains(&3));
537    ///
538    /// assert!( (0.0..=1.0).contains(&1.0));
539    /// assert!(!(0.0..=1.0).contains(&f32::NAN));
540    /// assert!(!(0.0..=f32::NAN).contains(&0.0));
541    /// assert!(!(f32::NAN..=1.0).contains(&1.0));
542    /// ```
543    ///
544    /// This method always returns `false` after iteration has finished:
545    ///
546    /// ```
547    /// let mut r = 3..=5;
548    /// assert!(r.contains(&3) && r.contains(&5));
549    /// for _ in r.by_ref() {}
550    /// // Precise field values are unspecified here
551    /// assert!(!r.contains(&3) && !r.contains(&5));
552    /// ```
553    #[inline]
554    #[stable(feature = "range_contains", since = "1.35.0")]
555    #[rustc_const_unstable(feature = "const_range", issue = "none")]
556    #[ferrocene::prevalidated]
557    pub const fn contains<U>(&self, item: &U) -> bool
558    where
559        Idx: [const] PartialOrd<U>,
560        U: ?Sized + [const] PartialOrd<Idx>,
561    {
562        <Self as RangeBounds<Idx>>::contains(self, item)
563    }
564
565    /// Returns `true` if the range contains no items.
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// assert!(!(3..=5).is_empty());
571    /// assert!(!(3..=3).is_empty());
572    /// assert!( (3..=2).is_empty());
573    /// ```
574    ///
575    /// The range is empty if either side is incomparable:
576    ///
577    /// ```
578    /// assert!(!(3.0..=5.0).is_empty());
579    /// assert!( (3.0..=f32::NAN).is_empty());
580    /// assert!( (f32::NAN..=5.0).is_empty());
581    /// ```
582    ///
583    /// This method returns `true` after iteration has finished:
584    ///
585    /// ```
586    /// let mut r = 3..=5;
587    /// for _ in r.by_ref() {}
588    /// // Precise field values are unspecified here
589    /// assert!(r.is_empty());
590    /// ```
591    #[ferrocene::prevalidated]
592    #[stable(feature = "range_is_empty", since = "1.47.0")]
593    #[inline]
594    #[rustc_const_unstable(feature = "const_range", issue = "none")]
595    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")]
596    pub const fn is_empty(&self) -> bool
597    where
598        Idx: [const] PartialOrd,
599    {
600        self.exhausted || !(self.start <= self.end)
601    }
602}
603
604/// A range only bounded inclusively above (`..=end`).
605///
606/// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
607/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
608///
609/// # Examples
610///
611/// The `..=end` syntax is a `RangeToInclusive`:
612///
613/// ```
614/// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
615/// ```
616///
617/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
618/// `for` loop directly. This won't compile:
619///
620/// ```compile_fail,E0277
621/// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
622/// // std::iter::Iterator` is not satisfied
623/// for i in ..=5 {
624///     // ...
625/// }
626/// ```
627///
628/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
629/// array elements up to and including the index indicated by `end`.
630///
631/// ```
632/// let arr = [0, 1, 2, 3, 4];
633/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
634/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
635/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]); // This is a `RangeToInclusive`
636/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
637/// assert_eq!(arr[1.. 3], [   1, 2      ]);
638/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
639/// ```
640///
641/// [slicing index]: crate::slice::SliceIndex
642#[lang = "RangeToInclusive"]
643#[doc(alias = "..=")]
644#[derive(Copy, Hash)]
645#[derive(Clone, PartialEq, Eq)]
646#[stable(feature = "inclusive_range", since = "1.26.0")]
647#[ferrocene::prevalidated]
648pub struct RangeToInclusive<Idx> {
649    /// The upper bound of the range (inclusive)
650    #[stable(feature = "inclusive_range", since = "1.26.0")]
651    pub end: Idx,
652}
653
654#[stable(feature = "inclusive_range", since = "1.26.0")]
655impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
656    #[ferrocene::prevalidated]
657    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
658        write!(fmt, "..=")?;
659        self.end.fmt(fmt)?;
660        Ok(())
661    }
662}
663
664impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
665    /// Returns `true` if `item` is contained in the range.
666    ///
667    /// # Examples
668    ///
669    /// ```
670    /// assert!( (..=5).contains(&-1_000_000_000));
671    /// assert!( (..=5).contains(&5));
672    /// assert!(!(..=5).contains(&6));
673    ///
674    /// assert!( (..=1.0).contains(&1.0));
675    /// assert!(!(..=1.0).contains(&f32::NAN));
676    /// assert!(!(..=f32::NAN).contains(&0.5));
677    /// ```
678    #[inline]
679    #[stable(feature = "range_contains", since = "1.35.0")]
680    #[rustc_const_unstable(feature = "const_range", issue = "none")]
681    pub const fn contains<U>(&self, item: &U) -> bool
682    where
683        Idx: [const] PartialOrd<U>,
684        U: ?Sized + [const] PartialOrd<Idx>,
685    {
686        <Self as RangeBounds<Idx>>::contains(self, item)
687    }
688}
689
690// RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
691// because underflow would be possible with (..0).into()
692
693/// An endpoint of a range of keys.
694///
695/// # Examples
696///
697/// `Bound`s are range endpoints:
698///
699/// ```
700/// use std::ops::Bound::*;
701/// use std::ops::RangeBounds;
702///
703/// assert_eq!((..100).start_bound(), Unbounded);
704/// assert_eq!((1..12).start_bound(), Included(&1));
705/// assert_eq!((1..12).end_bound(), Excluded(&12));
706/// ```
707///
708/// Using a tuple of `Bound`s as an argument to [`BTreeMap::range`].
709/// Note that in most cases, it's better to use range syntax (`1..5`) instead.
710///
711/// ```
712/// use std::collections::BTreeMap;
713/// use std::ops::Bound::{Excluded, Included, Unbounded};
714///
715/// let mut map = BTreeMap::new();
716/// map.insert(3, "a");
717/// map.insert(5, "b");
718/// map.insert(8, "c");
719///
720/// for (key, value) in map.range((Excluded(3), Included(8))) {
721///     println!("{key}: {value}");
722/// }
723///
724/// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());
725/// ```
726///
727/// [`BTreeMap::range`]: ../../std/collections/btree_map/struct.BTreeMap.html#method.range
728#[stable(feature = "collections_bound", since = "1.17.0")]
729#[derive(Copy, Debug, Hash)]
730#[derive_const(Clone, Eq, PartialEq)]
731#[ferrocene::prevalidated]
732pub enum Bound<T> {
733    /// An inclusive bound.
734    #[stable(feature = "collections_bound", since = "1.17.0")]
735    Included(#[stable(feature = "collections_bound", since = "1.17.0")] T),
736    /// An exclusive bound.
737    #[stable(feature = "collections_bound", since = "1.17.0")]
738    Excluded(#[stable(feature = "collections_bound", since = "1.17.0")] T),
739    /// An infinite endpoint. Indicates that there is no bound in this direction.
740    #[stable(feature = "collections_bound", since = "1.17.0")]
741    Unbounded,
742}
743
744impl<T> Bound<T> {
745    /// Converts from `&Bound<T>` to `Bound<&T>`.
746    #[inline]
747    #[stable(feature = "bound_as_ref_shared", since = "1.65.0")]
748    #[rustc_const_unstable(feature = "const_range", issue = "none")]
749    #[ferrocene::prevalidated]
750    pub const fn as_ref(&self) -> Bound<&T> {
751        match *self {
752            Included(ref x) => Included(x),
753            Excluded(ref x) => Excluded(x),
754            Unbounded => Unbounded,
755        }
756    }
757
758    /// Converts from `&mut Bound<T>` to `Bound<&mut T>`.
759    #[inline]
760    #[unstable(feature = "bound_as_ref", issue = "80996")]
761    #[ferrocene::prevalidated]
762    pub const fn as_mut(&mut self) -> Bound<&mut T> {
763        match *self {
764            Included(ref mut x) => Included(x),
765            Excluded(ref mut x) => Excluded(x),
766            Unbounded => Unbounded,
767        }
768    }
769
770    /// Maps a `Bound<T>` to a `Bound<U>` by applying a function to the contained value (including
771    /// both `Included` and `Excluded`), returning a `Bound` of the same kind.
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// use std::ops::Bound::*;
777    ///
778    /// let bound_string = Included("Hello, World!");
779    ///
780    /// assert_eq!(bound_string.map(|s| s.len()), Included(13));
781    /// ```
782    ///
783    /// ```
784    /// use std::ops::Bound;
785    /// use Bound::*;
786    ///
787    /// let unbounded_string: Bound<String> = Unbounded;
788    ///
789    /// assert_eq!(unbounded_string.map(|s| s.len()), Unbounded);
790    /// ```
791    #[inline]
792    #[stable(feature = "bound_map", since = "1.77.0")]
793    #[ferrocene::prevalidated]
794    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Bound<U> {
795        match self {
796            Unbounded => Unbounded,
797            Included(x) => Included(f(x)),
798            Excluded(x) => Excluded(f(x)),
799        }
800    }
801}
802
803impl<T: Copy> Bound<&T> {
804    /// Map a `Bound<&T>` to a `Bound<T>` by copying the contents of the bound.
805    ///
806    /// # Examples
807    ///
808    /// ```
809    /// #![feature(bound_copied)]
810    ///
811    /// use std::ops::Bound::*;
812    /// use std::ops::RangeBounds;
813    ///
814    /// assert_eq!((1..12).start_bound(), Included(&1));
815    /// assert_eq!((1..12).start_bound().copied(), Included(1));
816    /// ```
817    #[unstable(feature = "bound_copied", issue = "145966")]
818    #[must_use]
819    #[ferrocene::prevalidated]
820    pub const fn copied(self) -> Bound<T> {
821        match self {
822            Bound::Unbounded => Bound::Unbounded,
823            Bound::Included(x) => Bound::Included(*x),
824            Bound::Excluded(x) => Bound::Excluded(*x),
825        }
826    }
827}
828
829impl<T: Clone> Bound<&T> {
830    /// Map a `Bound<&T>` to a `Bound<T>` by cloning the contents of the bound.
831    ///
832    /// # Examples
833    ///
834    /// ```
835    /// use std::ops::Bound::*;
836    /// use std::ops::RangeBounds;
837    ///
838    /// let a1 = String::from("a");
839    /// let (a2, a3, a4) = (a1.clone(), a1.clone(), a1.clone());
840    ///
841    /// assert_eq!(Included(&a1), (a2..).start_bound());
842    /// assert_eq!(Included(a3), (a4..).start_bound().cloned());
843    /// ```
844    #[must_use = "`self` will be dropped if the result is not used"]
845    #[stable(feature = "bound_cloned", since = "1.55.0")]
846    #[rustc_const_unstable(feature = "const_range", issue = "none")]
847    #[ferrocene::prevalidated]
848    pub const fn cloned(self) -> Bound<T>
849    where
850        T: [const] Clone,
851    {
852        match self {
853            Bound::Unbounded => Bound::Unbounded,
854            Bound::Included(x) => Bound::Included(x.clone()),
855            Bound::Excluded(x) => Bound::Excluded(x.clone()),
856        }
857    }
858}
859
860/// `RangeBounds` is implemented by Rust's built-in range types, produced
861/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
862#[stable(feature = "collections_range", since = "1.28.0")]
863#[rustc_diagnostic_item = "RangeBounds"]
864#[rustc_const_unstable(feature = "const_range", issue = "none")]
865pub const trait RangeBounds<T: ?Sized> {
866    /// Start index bound.
867    ///
868    /// Returns the start value as a `Bound`.
869    ///
870    /// # Examples
871    ///
872    /// ```
873    /// use std::ops::Bound::*;
874    /// use std::ops::RangeBounds;
875    ///
876    /// assert_eq!((..10).start_bound(), Unbounded);
877    /// assert_eq!((3..10).start_bound(), Included(&3));
878    /// ```
879    #[stable(feature = "collections_range", since = "1.28.0")]
880    fn start_bound(&self) -> Bound<&T>;
881
882    /// End index bound.
883    ///
884    /// Returns the end value as a `Bound`.
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use std::ops::Bound::*;
890    /// use std::ops::RangeBounds;
891    ///
892    /// assert_eq!((3..).end_bound(), Unbounded);
893    /// assert_eq!((3..10).end_bound(), Excluded(&10));
894    /// ```
895    #[stable(feature = "collections_range", since = "1.28.0")]
896    fn end_bound(&self) -> Bound<&T>;
897
898    /// Returns `true` if `item` is contained in the range.
899    ///
900    /// # Examples
901    ///
902    /// ```
903    /// assert!( (3..5).contains(&4));
904    /// assert!(!(3..5).contains(&2));
905    ///
906    /// assert!( (0.0..1.0).contains(&0.5));
907    /// assert!(!(0.0..1.0).contains(&f32::NAN));
908    /// assert!(!(0.0..f32::NAN).contains(&0.5));
909    /// assert!(!(f32::NAN..1.0).contains(&0.5));
910    /// ```
911    #[inline]
912    #[stable(feature = "range_contains", since = "1.35.0")]
913    #[ferrocene::prevalidated]
914    fn contains<U>(&self, item: &U) -> bool
915    where
916        T: [const] PartialOrd<U>,
917        U: ?Sized + [const] PartialOrd<T>,
918    {
919        (match self.start_bound() {
920            Included(start) => start <= item,
921            Excluded(start) => start < item,
922            Unbounded => true,
923        }) && (match self.end_bound() {
924            Included(end) => item <= end,
925            Excluded(end) => item < end,
926            Unbounded => true,
927        })
928    }
929
930    /// Returns `true` if the range contains no items.
931    /// One-sided ranges (`RangeFrom`, etc) always return `false`.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// #![feature(range_bounds_is_empty)]
937    /// use std::ops::RangeBounds;
938    ///
939    /// assert!(!(3..).is_empty());
940    /// assert!(!(..2).is_empty());
941    /// assert!(!RangeBounds::is_empty(&(3..5)));
942    /// assert!( RangeBounds::is_empty(&(3..3)));
943    /// assert!( RangeBounds::is_empty(&(3..2)));
944    /// ```
945    ///
946    /// The range is empty if either side is incomparable:
947    ///
948    /// ```
949    /// #![feature(range_bounds_is_empty)]
950    /// use std::ops::RangeBounds;
951    ///
952    /// assert!(!RangeBounds::is_empty(&(3.0..5.0)));
953    /// assert!( RangeBounds::is_empty(&(3.0..f32::NAN)));
954    /// assert!( RangeBounds::is_empty(&(f32::NAN..5.0)));
955    /// ```
956    ///
957    /// But never empty if either side is unbounded:
958    ///
959    /// ```
960    /// #![feature(range_bounds_is_empty)]
961    /// use std::ops::RangeBounds;
962    ///
963    /// assert!(!(..0).is_empty());
964    /// assert!(!(i32::MAX..).is_empty());
965    /// assert!(!RangeBounds::<u8>::is_empty(&(..)));
966    /// ```
967    ///
968    /// `(Excluded(a), Excluded(b))` is only empty if `a >= b`:
969    ///
970    /// ```
971    /// #![feature(range_bounds_is_empty)]
972    /// use std::ops::Bound::*;
973    /// use std::ops::RangeBounds;
974    ///
975    /// assert!(!(Excluded(1), Excluded(3)).is_empty());
976    /// assert!(!(Excluded(1), Excluded(2)).is_empty());
977    /// assert!( (Excluded(1), Excluded(1)).is_empty());
978    /// assert!( (Excluded(2), Excluded(1)).is_empty());
979    /// assert!( (Excluded(3), Excluded(1)).is_empty());
980    /// ```
981    #[unstable(feature = "range_bounds_is_empty", issue = "137300")]
982    fn is_empty(&self) -> bool
983    where
984        T: [const] PartialOrd,
985    {
986        !match (self.start_bound(), self.end_bound()) {
987            (Unbounded, _) | (_, Unbounded) => true,
988            (Included(start), Excluded(end))
989            | (Excluded(start), Included(end))
990            | (Excluded(start), Excluded(end)) => start < end,
991            (Included(start), Included(end)) => start <= end,
992        }
993    }
994}
995
996/// Used to convert a range into start and end bounds, consuming the
997/// range by value.
998///
999/// `IntoBounds` is implemented by Rust’s built-in range types, produced
1000/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
1001#[unstable(feature = "range_into_bounds", issue = "136903")]
1002#[rustc_const_unstable(feature = "const_range", issue = "none")]
1003pub const trait IntoBounds<T>: [const] RangeBounds<T> {
1004    /// Convert this range into the start and end bounds.
1005    /// Returns `(start_bound, end_bound)`.
1006    ///
1007    /// # Examples
1008    ///
1009    /// ```
1010    /// #![feature(range_into_bounds)]
1011    /// use std::ops::Bound::*;
1012    /// use std::ops::IntoBounds;
1013    ///
1014    /// assert_eq!((0..5).into_bounds(), (Included(0), Excluded(5)));
1015    /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7)));
1016    /// ```
1017    fn into_bounds(self) -> (Bound<T>, Bound<T>);
1018
1019    /// Compute the intersection of  `self` and `other`.
1020    ///
1021    /// # Examples
1022    ///
1023    /// ```
1024    /// #![feature(range_into_bounds)]
1025    /// use std::ops::Bound::*;
1026    /// use std::ops::IntoBounds;
1027    ///
1028    /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5)));
1029    /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256)));
1030    /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5)));
1031    /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9)));
1032    /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13)));
1033    /// ```
1034    ///
1035    /// Combine with `is_empty` to determine if two ranges overlap.
1036    ///
1037    /// ```
1038    /// #![feature(range_into_bounds)]
1039    /// #![feature(range_bounds_is_empty)]
1040    /// use std::ops::{RangeBounds, IntoBounds};
1041    ///
1042    /// assert!(!(3..).intersect(..5).is_empty());
1043    /// assert!(!(-12..387).intersect(0..256).is_empty());
1044    /// assert!((1..5).intersect(6..).is_empty());
1045    /// ```
1046    fn intersect<R>(self, other: R) -> (Bound<T>, Bound<T>)
1047    where
1048        Self: Sized,
1049        T: [const] Ord + [const] Destruct,
1050        R: Sized + [const] IntoBounds<T>,
1051    {
1052        let (self_start, self_end) = IntoBounds::into_bounds(self);
1053        let (other_start, other_end) = IntoBounds::into_bounds(other);
1054
1055        let start = match (self_start, other_start) {
1056            (Included(a), Included(b)) => Included(Ord::max(a, b)),
1057            (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)),
1058            (Unbounded, Unbounded) => Unbounded,
1059
1060            (x, Unbounded) | (Unbounded, x) => x,
1061
1062            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1063                if i > e {
1064                    Included(i)
1065                } else {
1066                    Excluded(e)
1067                }
1068            }
1069        };
1070        let end = match (self_end, other_end) {
1071            (Included(a), Included(b)) => Included(Ord::min(a, b)),
1072            (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)),
1073            (Unbounded, Unbounded) => Unbounded,
1074
1075            (x, Unbounded) | (Unbounded, x) => x,
1076
1077            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1078                if i < e {
1079                    Included(i)
1080                } else {
1081                    Excluded(e)
1082                }
1083            }
1084        };
1085
1086        (start, end)
1087    }
1088}
1089
1090use self::Bound::{Excluded, Included, Unbounded};
1091
1092#[stable(feature = "collections_range", since = "1.28.0")]
1093#[rustc_const_unstable(feature = "const_range", issue = "none")]
1094const impl<T: ?Sized> RangeBounds<T> for RangeFull {
1095    #[ferrocene::prevalidated]
1096    fn start_bound(&self) -> Bound<&T> {
1097        Unbounded
1098    }
1099    #[ferrocene::prevalidated]
1100    fn end_bound(&self) -> Bound<&T> {
1101        Unbounded
1102    }
1103}
1104
1105#[unstable(feature = "range_into_bounds", issue = "136903")]
1106#[rustc_const_unstable(feature = "const_range", issue = "none")]
1107const impl<T> IntoBounds<T> for RangeFull {
1108    #[ferrocene::prevalidated]
1109    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1110        (Unbounded, Unbounded)
1111    }
1112}
1113
1114#[stable(feature = "collections_range", since = "1.28.0")]
1115#[rustc_const_unstable(feature = "const_range", issue = "none")]
1116const impl<T> RangeBounds<T> for RangeFrom<T> {
1117    #[ferrocene::prevalidated]
1118    fn start_bound(&self) -> Bound<&T> {
1119        Included(&self.start)
1120    }
1121    #[ferrocene::prevalidated]
1122    fn end_bound(&self) -> Bound<&T> {
1123        Unbounded
1124    }
1125}
1126
1127#[unstable(feature = "range_into_bounds", issue = "136903")]
1128#[rustc_const_unstable(feature = "const_range", issue = "none")]
1129const impl<T> IntoBounds<T> for RangeFrom<T> {
1130    #[ferrocene::prevalidated]
1131    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1132        (Included(self.start), Unbounded)
1133    }
1134}
1135
1136#[stable(feature = "collections_range", since = "1.28.0")]
1137#[rustc_const_unstable(feature = "const_range", issue = "none")]
1138const impl<T> RangeBounds<T> for RangeTo<T> {
1139    #[ferrocene::prevalidated]
1140    fn start_bound(&self) -> Bound<&T> {
1141        Unbounded
1142    }
1143    #[ferrocene::prevalidated]
1144    fn end_bound(&self) -> Bound<&T> {
1145        Excluded(&self.end)
1146    }
1147}
1148
1149#[unstable(feature = "range_into_bounds", issue = "136903")]
1150#[rustc_const_unstable(feature = "const_range", issue = "none")]
1151const impl<T> IntoBounds<T> for RangeTo<T> {
1152    #[ferrocene::prevalidated]
1153    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1154        (Unbounded, Excluded(self.end))
1155    }
1156}
1157
1158#[stable(feature = "collections_range", since = "1.28.0")]
1159#[rustc_const_unstable(feature = "const_range", issue = "none")]
1160const impl<T> RangeBounds<T> for Range<T> {
1161    #[ferrocene::prevalidated]
1162    fn start_bound(&self) -> Bound<&T> {
1163        Included(&self.start)
1164    }
1165    #[ferrocene::prevalidated]
1166    fn end_bound(&self) -> Bound<&T> {
1167        Excluded(&self.end)
1168    }
1169}
1170
1171#[unstable(feature = "range_into_bounds", issue = "136903")]
1172#[rustc_const_unstable(feature = "const_range", issue = "none")]
1173const impl<T> IntoBounds<T> for Range<T> {
1174    #[ferrocene::prevalidated]
1175    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1176        (Included(self.start), Excluded(self.end))
1177    }
1178}
1179
1180#[stable(feature = "collections_range", since = "1.28.0")]
1181#[rustc_const_unstable(feature = "const_range", issue = "none")]
1182const impl<T> RangeBounds<T> for RangeInclusive<T> {
1183    #[ferrocene::prevalidated]
1184    fn start_bound(&self) -> Bound<&T> {
1185        Included(&self.start)
1186    }
1187    #[ferrocene::prevalidated]
1188    fn end_bound(&self) -> Bound<&T> {
1189        if self.exhausted {
1190            // When the iterator is exhausted, it might have overflowed,
1191            // but we want the range to appear empty, containing nothing.
1192            // So in that case, we return bounds which are always empty:
1193            // Included(start)..Excluded(start)
1194            Excluded(&self.start)
1195        } else {
1196            Included(&self.end)
1197        }
1198    }
1199}
1200
1201#[unstable(feature = "range_into_bounds", issue = "136903")]
1202#[rustc_const_unstable(feature = "const_range", issue = "none")]
1203const impl<T> IntoBounds<T> for RangeInclusive<T> {
1204    #[ferrocene::prevalidated]
1205    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1206        assert!(
1207            !self.exhausted,
1208            "attempted to convert from an exhausted `RangeInclusive` (unspecified behavior)"
1209        );
1210
1211        (Included(self.start), Included(self.end))
1212    }
1213}
1214
1215#[stable(feature = "collections_range", since = "1.28.0")]
1216#[rustc_const_unstable(feature = "const_range", issue = "none")]
1217const impl<T> RangeBounds<T> for RangeToInclusive<T> {
1218    #[ferrocene::prevalidated]
1219    fn start_bound(&self) -> Bound<&T> {
1220        Unbounded
1221    }
1222    #[ferrocene::prevalidated]
1223    fn end_bound(&self) -> Bound<&T> {
1224        Included(&self.end)
1225    }
1226}
1227
1228#[unstable(feature = "range_into_bounds", issue = "136903")]
1229#[rustc_const_unstable(feature = "const_range", issue = "none")]
1230const impl<T> IntoBounds<T> for RangeToInclusive<T> {
1231    #[ferrocene::prevalidated]
1232    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1233        (Unbounded, Included(self.end))
1234    }
1235}
1236
1237#[stable(feature = "collections_range", since = "1.28.0")]
1238#[rustc_const_unstable(feature = "const_range", issue = "none")]
1239const impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
1240    #[ferrocene::prevalidated]
1241    fn start_bound(&self) -> Bound<&T> {
1242        match *self {
1243            (Included(ref start), _) => Included(start),
1244            (Excluded(ref start), _) => Excluded(start),
1245            (Unbounded, _) => Unbounded,
1246        }
1247    }
1248
1249    #[ferrocene::prevalidated]
1250    fn end_bound(&self) -> Bound<&T> {
1251        match *self {
1252            (_, Included(ref end)) => Included(end),
1253            (_, Excluded(ref end)) => Excluded(end),
1254            (_, Unbounded) => Unbounded,
1255        }
1256    }
1257}
1258
1259#[unstable(feature = "range_into_bounds", issue = "136903")]
1260#[rustc_const_unstable(feature = "const_range", issue = "none")]
1261const impl<T> IntoBounds<T> for (Bound<T>, Bound<T>) {
1262    #[ferrocene::prevalidated]
1263    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1264        self
1265    }
1266}
1267
1268#[stable(feature = "collections_range", since = "1.28.0")]
1269#[rustc_const_unstable(feature = "const_range", issue = "none")]
1270const impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
1271    fn start_bound(&self) -> Bound<&T> {
1272        self.0
1273    }
1274
1275    fn end_bound(&self) -> Bound<&T> {
1276        self.1
1277    }
1278}
1279
1280// This impl intentionally does not have `T: ?Sized`;
1281// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1282//
1283/// If you need to use this implementation where `T` is unsized,
1284/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1285/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`.
1286#[stable(feature = "collections_range", since = "1.28.0")]
1287#[rustc_const_unstable(feature = "const_range", issue = "none")]
1288const impl<T> RangeBounds<T> for RangeFrom<&T> {
1289    #[ferrocene::prevalidated]
1290    fn start_bound(&self) -> Bound<&T> {
1291        Included(self.start)
1292    }
1293    #[ferrocene::prevalidated]
1294    fn end_bound(&self) -> Bound<&T> {
1295        Unbounded
1296    }
1297}
1298
1299// This impl intentionally does not have `T: ?Sized`;
1300// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1301//
1302/// If you need to use this implementation where `T` is unsized,
1303/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1304/// i.e. replace `..end` with `(Bound::Unbounded, Bound::Excluded(end))`.
1305#[stable(feature = "collections_range", since = "1.28.0")]
1306#[rustc_const_unstable(feature = "const_range", issue = "none")]
1307const impl<T> RangeBounds<T> for RangeTo<&T> {
1308    #[ferrocene::prevalidated]
1309    fn start_bound(&self) -> Bound<&T> {
1310        Unbounded
1311    }
1312    #[ferrocene::prevalidated]
1313    fn end_bound(&self) -> Bound<&T> {
1314        Excluded(self.end)
1315    }
1316}
1317
1318// This impl intentionally does not have `T: ?Sized`;
1319// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1320//
1321/// If you need to use this implementation where `T` is unsized,
1322/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1323/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`.
1324#[stable(feature = "collections_range", since = "1.28.0")]
1325#[rustc_const_unstable(feature = "const_range", issue = "none")]
1326const impl<T> RangeBounds<T> for Range<&T> {
1327    #[ferrocene::prevalidated]
1328    fn start_bound(&self) -> Bound<&T> {
1329        Included(self.start)
1330    }
1331    #[ferrocene::prevalidated]
1332    fn end_bound(&self) -> Bound<&T> {
1333        Excluded(self.end)
1334    }
1335}
1336
1337// This impl intentionally does not have `T: ?Sized`;
1338// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1339//
1340/// If you need to use this implementation where `T` is unsized,
1341/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1342/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`.
1343#[stable(feature = "collections_range", since = "1.28.0")]
1344#[rustc_const_unstable(feature = "const_range", issue = "none")]
1345const impl<T> RangeBounds<T> for RangeInclusive<&T> {
1346    #[ferrocene::prevalidated]
1347    fn start_bound(&self) -> Bound<&T> {
1348        Included(self.start)
1349    }
1350    #[ferrocene::prevalidated]
1351    fn end_bound(&self) -> Bound<&T> {
1352        Included(self.end)
1353    }
1354}
1355
1356// This impl intentionally does not have `T: ?Sized`;
1357// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1358//
1359/// If you need to use this implementation where `T` is unsized,
1360/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1361/// i.e. replace `..=end` with `(Bound::Unbounded, Bound::Included(end))`.
1362#[stable(feature = "collections_range", since = "1.28.0")]
1363#[rustc_const_unstable(feature = "const_range", issue = "none")]
1364const impl<T> RangeBounds<T> for RangeToInclusive<&T> {
1365    #[ferrocene::prevalidated]
1366    fn start_bound(&self) -> Bound<&T> {
1367        Unbounded
1368    }
1369    #[ferrocene::prevalidated]
1370    fn end_bound(&self) -> Bound<&T> {
1371        Included(self.end)
1372    }
1373}
1374
1375/// An internal helper for `split_off` functions indicating
1376/// which end a `OneSidedRange` is bounded on.
1377#[unstable(feature = "one_sided_range", issue = "69780")]
1378#[allow(missing_debug_implementations)]
1379#[ferrocene::prevalidated]
1380pub enum OneSidedRangeBound {
1381    /// The range is bounded inclusively from below and is unbounded above.
1382    StartInclusive,
1383    /// The range is bounded exclusively from above and is unbounded below.
1384    End,
1385    /// The range is bounded inclusively from above and is unbounded below.
1386    EndInclusive,
1387}
1388
1389/// `OneSidedRange` is implemented for built-in range types that are unbounded
1390/// on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`,
1391/// but `..`, `d..e`, and `f..=g` do not.
1392///
1393/// Types that implement `OneSidedRange<T>` must return `Bound::Unbounded`
1394/// from one of `RangeBounds::start_bound` or `RangeBounds::end_bound`.
1395#[unstable(feature = "one_sided_range", issue = "69780")]
1396#[rustc_const_unstable(feature = "const_range", issue = "none")]
1397pub const trait OneSidedRange<T>: RangeBounds<T> {
1398    /// An internal-only helper function for `split_off` and
1399    /// `split_off_mut` that returns the bound of the one-sided range.
1400    fn bound(self) -> (OneSidedRangeBound, T);
1401}
1402
1403#[unstable(feature = "one_sided_range", issue = "69780")]
1404#[rustc_const_unstable(feature = "const_range", issue = "none")]
1405const impl<T> OneSidedRange<T> for RangeTo<T>
1406where
1407    Self: RangeBounds<T>,
1408{
1409    #[ferrocene::prevalidated]
1410    fn bound(self) -> (OneSidedRangeBound, T) {
1411        (OneSidedRangeBound::End, self.end)
1412    }
1413}
1414
1415#[unstable(feature = "one_sided_range", issue = "69780")]
1416#[rustc_const_unstable(feature = "const_range", issue = "none")]
1417const impl<T> OneSidedRange<T> for RangeFrom<T>
1418where
1419    Self: RangeBounds<T>,
1420{
1421    #[ferrocene::prevalidated]
1422    fn bound(self) -> (OneSidedRangeBound, T) {
1423        (OneSidedRangeBound::StartInclusive, self.start)
1424    }
1425}
1426
1427#[unstable(feature = "one_sided_range", issue = "69780")]
1428#[rustc_const_unstable(feature = "const_range", issue = "none")]
1429const impl<T> OneSidedRange<T> for RangeToInclusive<T>
1430where
1431    Self: RangeBounds<T>,
1432{
1433    #[ferrocene::prevalidated]
1434    fn bound(self) -> (OneSidedRangeBound, T) {
1435        (OneSidedRangeBound::EndInclusive, self.end)
1436    }
1437}