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#[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
106impl<Idx: PartialOrd<Idx>> Range<Idx> {
107    /// Returns `true` if `item` is contained in the range.
108    ///
109    /// # Examples
110    ///
111    /// ```
112    /// assert!(!(3..5).contains(&2));
113    /// assert!( (3..5).contains(&3));
114    /// assert!( (3..5).contains(&4));
115    /// assert!(!(3..5).contains(&5));
116    ///
117    /// assert!(!(3..3).contains(&3));
118    /// assert!(!(3..2).contains(&3));
119    ///
120    /// assert!( (0.0..1.0).contains(&0.5));
121    /// assert!(!(0.0..1.0).contains(&f32::NAN));
122    /// assert!(!(0.0..f32::NAN).contains(&0.5));
123    /// assert!(!(f32::NAN..1.0).contains(&0.5));
124    /// ```
125    #[inline]
126    #[stable(feature = "range_contains", since = "1.35.0")]
127    #[rustc_const_unstable(feature = "const_range", issue = "none")]
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    #[cfg(not(feature = "ferrocene_certified"))]
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#[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
500impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
501    /// Returns `true` if `item` is contained in the range.
502    ///
503    /// # Examples
504    ///
505    /// ```
506    /// assert!(!(3..=5).contains(&2));
507    /// assert!( (3..=5).contains(&3));
508    /// assert!( (3..=5).contains(&4));
509    /// assert!( (3..=5).contains(&5));
510    /// assert!(!(3..=5).contains(&6));
511    ///
512    /// assert!( (3..=3).contains(&3));
513    /// assert!(!(3..=2).contains(&3));
514    ///
515    /// assert!( (0.0..=1.0).contains(&1.0));
516    /// assert!(!(0.0..=1.0).contains(&f32::NAN));
517    /// assert!(!(0.0..=f32::NAN).contains(&0.0));
518    /// assert!(!(f32::NAN..=1.0).contains(&1.0));
519    /// ```
520    ///
521    /// This method always returns `false` after iteration has finished:
522    ///
523    /// ```
524    /// let mut r = 3..=5;
525    /// assert!(r.contains(&3) && r.contains(&5));
526    /// for _ in r.by_ref() {}
527    /// // Precise field values are unspecified here
528    /// assert!(!r.contains(&3) && !r.contains(&5));
529    /// ```
530    #[inline]
531    #[stable(feature = "range_contains", since = "1.35.0")]
532    #[rustc_const_unstable(feature = "const_range", issue = "none")]
533    pub const fn contains<U>(&self, item: &U) -> bool
534    where
535        Idx: [const] PartialOrd<U>,
536        U: ?Sized + [const] PartialOrd<Idx>,
537    {
538        <Self as RangeBounds<Idx>>::contains(self, item)
539    }
540
541    /// Returns `true` if the range contains no items.
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// assert!(!(3..=5).is_empty());
547    /// assert!(!(3..=3).is_empty());
548    /// assert!( (3..=2).is_empty());
549    /// ```
550    ///
551    /// The range is empty if either side is incomparable:
552    ///
553    /// ```
554    /// assert!(!(3.0..=5.0).is_empty());
555    /// assert!( (3.0..=f32::NAN).is_empty());
556    /// assert!( (f32::NAN..=5.0).is_empty());
557    /// ```
558    ///
559    /// This method returns `true` after iteration has finished:
560    ///
561    /// ```
562    /// let mut r = 3..=5;
563    /// for _ in r.by_ref() {}
564    /// // Precise field values are unspecified here
565    /// assert!(r.is_empty());
566    /// ```
567    #[stable(feature = "range_is_empty", since = "1.47.0")]
568    #[inline]
569    #[rustc_const_unstable(feature = "const_range", issue = "none")]
570    #[cfg(not(feature = "ferrocene_certified"))]
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    fn contains<U>(&self, item: &U) -> bool
883    where
884        T: [const] PartialOrd<U>,
885        U: ?Sized + [const] PartialOrd<T>,
886    {
887        (match self.start_bound() {
888            Included(start) => start <= item,
889            Excluded(start) => start < item,
890            Unbounded => true,
891        }) && (match self.end_bound() {
892            Included(end) => item <= end,
893            Excluded(end) => item < end,
894            Unbounded => true,
895        })
896    }
897
898    /// Returns `true` if the range contains no items.
899    /// One-sided ranges (`RangeFrom`, etc) always return `false`.
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// #![feature(range_bounds_is_empty)]
905    /// use std::ops::RangeBounds;
906    ///
907    /// assert!(!(3..).is_empty());
908    /// assert!(!(..2).is_empty());
909    /// assert!(!RangeBounds::is_empty(&(3..5)));
910    /// assert!( RangeBounds::is_empty(&(3..3)));
911    /// assert!( RangeBounds::is_empty(&(3..2)));
912    /// ```
913    ///
914    /// The range is empty if either side is incomparable:
915    ///
916    /// ```
917    /// #![feature(range_bounds_is_empty)]
918    /// use std::ops::RangeBounds;
919    ///
920    /// assert!(!RangeBounds::is_empty(&(3.0..5.0)));
921    /// assert!( RangeBounds::is_empty(&(3.0..f32::NAN)));
922    /// assert!( RangeBounds::is_empty(&(f32::NAN..5.0)));
923    /// ```
924    ///
925    /// But never empty if either side is unbounded:
926    ///
927    /// ```
928    /// #![feature(range_bounds_is_empty)]
929    /// use std::ops::RangeBounds;
930    ///
931    /// assert!(!(..0).is_empty());
932    /// assert!(!(i32::MAX..).is_empty());
933    /// assert!(!RangeBounds::<u8>::is_empty(&(..)));
934    /// ```
935    ///
936    /// `(Excluded(a), Excluded(b))` is only empty if `a >= b`:
937    ///
938    /// ```
939    /// #![feature(range_bounds_is_empty)]
940    /// use std::ops::Bound::*;
941    /// use std::ops::RangeBounds;
942    ///
943    /// assert!(!(Excluded(1), Excluded(3)).is_empty());
944    /// assert!(!(Excluded(1), Excluded(2)).is_empty());
945    /// assert!( (Excluded(1), Excluded(1)).is_empty());
946    /// assert!( (Excluded(2), Excluded(1)).is_empty());
947    /// assert!( (Excluded(3), Excluded(1)).is_empty());
948    /// ```
949    #[unstable(feature = "range_bounds_is_empty", issue = "137300")]
950    #[cfg(not(feature = "ferrocene_certified"))]
951    fn is_empty(&self) -> bool
952    where
953        T: [const] PartialOrd,
954    {
955        !match (self.start_bound(), self.end_bound()) {
956            (Unbounded, _) | (_, Unbounded) => true,
957            (Included(start), Excluded(end))
958            | (Excluded(start), Included(end))
959            | (Excluded(start), Excluded(end)) => start < end,
960            (Included(start), Included(end)) => start <= end,
961        }
962    }
963}
964
965/// Used to convert a range into start and end bounds, consuming the
966/// range by value.
967///
968/// `IntoBounds` is implemented by Rust’s built-in range types, produced
969/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
970#[unstable(feature = "range_into_bounds", issue = "136903")]
971#[rustc_const_unstable(feature = "const_range", issue = "none")]
972pub const trait IntoBounds<T>: [const] RangeBounds<T> {
973    /// Convert this range into the start and end bounds.
974    /// Returns `(start_bound, end_bound)`.
975    ///
976    /// # Examples
977    ///
978    /// ```
979    /// #![feature(range_into_bounds)]
980    /// use std::ops::Bound::*;
981    /// use std::ops::IntoBounds;
982    ///
983    /// assert_eq!((0..5).into_bounds(), (Included(0), Excluded(5)));
984    /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7)));
985    /// ```
986    fn into_bounds(self) -> (Bound<T>, Bound<T>);
987
988    /// Compute the intersection of  `self` and `other`.
989    ///
990    /// # Examples
991    ///
992    /// ```
993    /// #![feature(range_into_bounds)]
994    /// use std::ops::Bound::*;
995    /// use std::ops::IntoBounds;
996    ///
997    /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5)));
998    /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256)));
999    /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5)));
1000    /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9)));
1001    /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13)));
1002    /// ```
1003    ///
1004    /// Combine with `is_empty` to determine if two ranges overlap.
1005    ///
1006    /// ```
1007    /// #![feature(range_into_bounds)]
1008    /// #![feature(range_bounds_is_empty)]
1009    /// use std::ops::{RangeBounds, IntoBounds};
1010    ///
1011    /// assert!(!(3..).intersect(..5).is_empty());
1012    /// assert!(!(-12..387).intersect(0..256).is_empty());
1013    /// assert!((1..5).intersect(6..).is_empty());
1014    /// ```
1015    #[cfg(not(feature = "ferrocene_certified"))]
1016    fn intersect<R>(self, other: R) -> (Bound<T>, Bound<T>)
1017    where
1018        Self: Sized,
1019        T: [const] Ord + [const] Destruct,
1020        R: Sized + [const] IntoBounds<T>,
1021    {
1022        let (self_start, self_end) = IntoBounds::into_bounds(self);
1023        let (other_start, other_end) = IntoBounds::into_bounds(other);
1024
1025        let start = match (self_start, other_start) {
1026            (Included(a), Included(b)) => Included(Ord::max(a, b)),
1027            (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)),
1028            (Unbounded, Unbounded) => Unbounded,
1029
1030            (x, Unbounded) | (Unbounded, x) => x,
1031
1032            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1033                if i > e {
1034                    Included(i)
1035                } else {
1036                    Excluded(e)
1037                }
1038            }
1039        };
1040        let end = match (self_end, other_end) {
1041            (Included(a), Included(b)) => Included(Ord::min(a, b)),
1042            (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)),
1043            (Unbounded, Unbounded) => Unbounded,
1044
1045            (x, Unbounded) | (Unbounded, x) => x,
1046
1047            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1048                if i < e {
1049                    Included(i)
1050                } else {
1051                    Excluded(e)
1052                }
1053            }
1054        };
1055
1056        (start, end)
1057    }
1058}
1059
1060use self::Bound::{Excluded, Included, Unbounded};
1061
1062#[stable(feature = "collections_range", since = "1.28.0")]
1063#[rustc_const_unstable(feature = "const_range", issue = "none")]
1064impl<T: ?Sized> const RangeBounds<T> for RangeFull {
1065    fn start_bound(&self) -> Bound<&T> {
1066        Unbounded
1067    }
1068    fn end_bound(&self) -> Bound<&T> {
1069        Unbounded
1070    }
1071}
1072
1073#[unstable(feature = "range_into_bounds", issue = "136903")]
1074#[rustc_const_unstable(feature = "const_range", issue = "none")]
1075impl<T> const IntoBounds<T> for RangeFull {
1076    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1077        (Unbounded, Unbounded)
1078    }
1079}
1080
1081#[stable(feature = "collections_range", since = "1.28.0")]
1082#[rustc_const_unstable(feature = "const_range", issue = "none")]
1083impl<T> const RangeBounds<T> for RangeFrom<T> {
1084    fn start_bound(&self) -> Bound<&T> {
1085        Included(&self.start)
1086    }
1087    fn end_bound(&self) -> Bound<&T> {
1088        Unbounded
1089    }
1090}
1091
1092#[unstable(feature = "range_into_bounds", issue = "136903")]
1093#[rustc_const_unstable(feature = "const_range", issue = "none")]
1094impl<T> const IntoBounds<T> for RangeFrom<T> {
1095    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1096        (Included(self.start), Unbounded)
1097    }
1098}
1099
1100#[stable(feature = "collections_range", since = "1.28.0")]
1101#[rustc_const_unstable(feature = "const_range", issue = "none")]
1102impl<T> const RangeBounds<T> for RangeTo<T> {
1103    fn start_bound(&self) -> Bound<&T> {
1104        Unbounded
1105    }
1106    fn end_bound(&self) -> Bound<&T> {
1107        Excluded(&self.end)
1108    }
1109}
1110
1111#[unstable(feature = "range_into_bounds", issue = "136903")]
1112#[rustc_const_unstable(feature = "const_range", issue = "none")]
1113impl<T> const IntoBounds<T> for RangeTo<T> {
1114    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1115        (Unbounded, Excluded(self.end))
1116    }
1117}
1118
1119#[stable(feature = "collections_range", since = "1.28.0")]
1120#[rustc_const_unstable(feature = "const_range", issue = "none")]
1121impl<T> const RangeBounds<T> for Range<T> {
1122    fn start_bound(&self) -> Bound<&T> {
1123        Included(&self.start)
1124    }
1125    fn end_bound(&self) -> Bound<&T> {
1126        Excluded(&self.end)
1127    }
1128}
1129
1130#[unstable(feature = "range_into_bounds", issue = "136903")]
1131#[rustc_const_unstable(feature = "const_range", issue = "none")]
1132impl<T> const IntoBounds<T> for Range<T> {
1133    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1134        (Included(self.start), Excluded(self.end))
1135    }
1136}
1137
1138#[stable(feature = "collections_range", since = "1.28.0")]
1139#[rustc_const_unstable(feature = "const_range", issue = "none")]
1140impl<T> const RangeBounds<T> for RangeInclusive<T> {
1141    fn start_bound(&self) -> Bound<&T> {
1142        Included(&self.start)
1143    }
1144    fn end_bound(&self) -> Bound<&T> {
1145        if self.exhausted {
1146            // When the iterator is exhausted, we usually have start == end,
1147            // but we want the range to appear empty, containing nothing.
1148            Excluded(&self.end)
1149        } else {
1150            Included(&self.end)
1151        }
1152    }
1153}
1154
1155#[unstable(feature = "range_into_bounds", issue = "136903")]
1156#[rustc_const_unstable(feature = "const_range", issue = "none")]
1157impl<T> const IntoBounds<T> for RangeInclusive<T> {
1158    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1159        (
1160            Included(self.start),
1161            if self.exhausted {
1162                // When the iterator is exhausted, we usually have start == end,
1163                // but we want the range to appear empty, containing nothing.
1164                Excluded(self.end)
1165            } else {
1166                Included(self.end)
1167            },
1168        )
1169    }
1170}
1171
1172#[stable(feature = "collections_range", since = "1.28.0")]
1173#[rustc_const_unstable(feature = "const_range", issue = "none")]
1174impl<T> const RangeBounds<T> for RangeToInclusive<T> {
1175    fn start_bound(&self) -> Bound<&T> {
1176        Unbounded
1177    }
1178    fn end_bound(&self) -> Bound<&T> {
1179        Included(&self.end)
1180    }
1181}
1182
1183#[unstable(feature = "range_into_bounds", issue = "136903")]
1184#[rustc_const_unstable(feature = "const_range", issue = "none")]
1185impl<T> const IntoBounds<T> for RangeToInclusive<T> {
1186    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1187        (Unbounded, Included(self.end))
1188    }
1189}
1190
1191#[stable(feature = "collections_range", since = "1.28.0")]
1192#[rustc_const_unstable(feature = "const_range", issue = "none")]
1193impl<T> const RangeBounds<T> for (Bound<T>, Bound<T>) {
1194    fn start_bound(&self) -> Bound<&T> {
1195        match *self {
1196            (Included(ref start), _) => Included(start),
1197            (Excluded(ref start), _) => Excluded(start),
1198            (Unbounded, _) => Unbounded,
1199        }
1200    }
1201
1202    fn end_bound(&self) -> Bound<&T> {
1203        match *self {
1204            (_, Included(ref end)) => Included(end),
1205            (_, Excluded(ref end)) => Excluded(end),
1206            (_, Unbounded) => Unbounded,
1207        }
1208    }
1209}
1210
1211#[unstable(feature = "range_into_bounds", issue = "136903")]
1212#[rustc_const_unstable(feature = "const_range", issue = "none")]
1213impl<T> const IntoBounds<T> for (Bound<T>, Bound<T>) {
1214    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1215        self
1216    }
1217}
1218
1219#[stable(feature = "collections_range", since = "1.28.0")]
1220#[rustc_const_unstable(feature = "const_range", issue = "none")]
1221#[cfg(not(feature = "ferrocene_certified"))]
1222impl<'a, T: ?Sized + 'a> const RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
1223    fn start_bound(&self) -> Bound<&T> {
1224        self.0
1225    }
1226
1227    fn end_bound(&self) -> Bound<&T> {
1228        self.1
1229    }
1230}
1231
1232// This impl intentionally does not have `T: ?Sized`;
1233// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1234//
1235/// If you need to use this implementation where `T` is unsized,
1236/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1237/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`.
1238#[stable(feature = "collections_range", since = "1.28.0")]
1239#[rustc_const_unstable(feature = "const_range", issue = "none")]
1240impl<T> const RangeBounds<T> for RangeFrom<&T> {
1241    fn start_bound(&self) -> Bound<&T> {
1242        Included(self.start)
1243    }
1244    fn end_bound(&self) -> Bound<&T> {
1245        Unbounded
1246    }
1247}
1248
1249// This impl intentionally does not have `T: ?Sized`;
1250// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1251//
1252/// If you need to use this implementation where `T` is unsized,
1253/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1254/// i.e. replace `..end` with `(Bound::Unbounded, Bound::Excluded(end))`.
1255#[stable(feature = "collections_range", since = "1.28.0")]
1256#[rustc_const_unstable(feature = "const_range", issue = "none")]
1257impl<T> const RangeBounds<T> for RangeTo<&T> {
1258    fn start_bound(&self) -> Bound<&T> {
1259        Unbounded
1260    }
1261    fn end_bound(&self) -> Bound<&T> {
1262        Excluded(self.end)
1263    }
1264}
1265
1266// This impl intentionally does not have `T: ?Sized`;
1267// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1268//
1269/// If you need to use this implementation where `T` is unsized,
1270/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1271/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`.
1272#[stable(feature = "collections_range", since = "1.28.0")]
1273#[rustc_const_unstable(feature = "const_range", issue = "none")]
1274impl<T> const RangeBounds<T> for Range<&T> {
1275    fn start_bound(&self) -> Bound<&T> {
1276        Included(self.start)
1277    }
1278    fn end_bound(&self) -> Bound<&T> {
1279        Excluded(self.end)
1280    }
1281}
1282
1283// This impl intentionally does not have `T: ?Sized`;
1284// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1285//
1286/// If you need to use this implementation where `T` is unsized,
1287/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1288/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`.
1289#[stable(feature = "collections_range", since = "1.28.0")]
1290#[rustc_const_unstable(feature = "const_range", issue = "none")]
1291impl<T> const RangeBounds<T> for RangeInclusive<&T> {
1292    fn start_bound(&self) -> Bound<&T> {
1293        Included(self.start)
1294    }
1295    fn end_bound(&self) -> Bound<&T> {
1296        Included(self.end)
1297    }
1298}
1299
1300// This impl intentionally does not have `T: ?Sized`;
1301// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1302//
1303/// If you need to use this implementation where `T` is unsized,
1304/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1305/// i.e. replace `..=end` with `(Bound::Unbounded, Bound::Included(end))`.
1306#[stable(feature = "collections_range", since = "1.28.0")]
1307#[rustc_const_unstable(feature = "const_range", issue = "none")]
1308impl<T> const RangeBounds<T> for RangeToInclusive<&T> {
1309    fn start_bound(&self) -> Bound<&T> {
1310        Unbounded
1311    }
1312    fn end_bound(&self) -> Bound<&T> {
1313        Included(self.end)
1314    }
1315}
1316
1317/// An internal helper for `split_off` functions indicating
1318/// which end a `OneSidedRange` is bounded on.
1319#[unstable(feature = "one_sided_range", issue = "69780")]
1320#[allow(missing_debug_implementations)]
1321pub enum OneSidedRangeBound {
1322    /// The range is bounded inclusively from below and is unbounded above.
1323    StartInclusive,
1324    /// The range is bounded exclusively from above and is unbounded below.
1325    End,
1326    /// The range is bounded inclusively from above and is unbounded below.
1327    EndInclusive,
1328}
1329
1330/// `OneSidedRange` is implemented for built-in range types that are unbounded
1331/// on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`,
1332/// but `..`, `d..e`, and `f..=g` do not.
1333///
1334/// Types that implement `OneSidedRange<T>` must return `Bound::Unbounded`
1335/// from one of `RangeBounds::start_bound` or `RangeBounds::end_bound`.
1336#[unstable(feature = "one_sided_range", issue = "69780")]
1337#[rustc_const_unstable(feature = "const_range", issue = "none")]
1338pub const trait OneSidedRange<T>: RangeBounds<T> {
1339    /// An internal-only helper function for `split_off` and
1340    /// `split_off_mut` that returns the bound of the one-sided range.
1341    fn bound(self) -> (OneSidedRangeBound, T);
1342}
1343
1344#[unstable(feature = "one_sided_range", issue = "69780")]
1345#[rustc_const_unstable(feature = "const_range", issue = "none")]
1346impl<T> const OneSidedRange<T> for RangeTo<T>
1347where
1348    Self: RangeBounds<T>,
1349{
1350    fn bound(self) -> (OneSidedRangeBound, T) {
1351        (OneSidedRangeBound::End, self.end)
1352    }
1353}
1354
1355#[unstable(feature = "one_sided_range", issue = "69780")]
1356#[rustc_const_unstable(feature = "const_range", issue = "none")]
1357impl<T> const OneSidedRange<T> for RangeFrom<T>
1358where
1359    Self: RangeBounds<T>,
1360{
1361    fn bound(self) -> (OneSidedRangeBound, T) {
1362        (OneSidedRangeBound::StartInclusive, self.start)
1363    }
1364}
1365
1366#[unstable(feature = "one_sided_range", issue = "69780")]
1367#[rustc_const_unstable(feature = "const_range", issue = "none")]
1368impl<T> const OneSidedRange<T> for RangeToInclusive<T>
1369where
1370    Self: RangeBounds<T>,
1371{
1372    fn bound(self) -> (OneSidedRangeBound, T) {
1373        (OneSidedRangeBound::EndInclusive, self.end)
1374    }
1375}