core/ops/
range.rs

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