Skip to main content

core/ops/
range.rs

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