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