Skip to main content

core/ops/
range.rs

1use crate::fmt;
2use crate::hash::Hash;
3use crate::marker::Destruct;
4/// An unbounded range (`..`).
5///
6/// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`.
7/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
8///
9/// # Examples
10///
11/// The `..` syntax is a `RangeFull`:
12///
13/// ```
14/// assert_eq!(.., std::ops::RangeFull);
15/// ```
16///
17/// It does not have an [`IntoIterator`] implementation, so you can't use it in
18/// a `for` loop directly. This won't compile:
19///
20/// ```compile_fail,E0277
21/// for i in .. {
22///     // ...
23/// }
24/// ```
25///
26/// Used as a [slicing index], `RangeFull` produces the full array as a slice.
27///
28/// ```
29/// let arr = [0, 1, 2, 3, 4];
30/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]); // This is the `RangeFull`
31/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
32/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
33/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
34/// assert_eq!(arr[1.. 3], [   1, 2      ]);
35/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
36/// ```
37///
38/// [slicing index]: crate::slice::SliceIndex
39#[lang = "RangeFull"]
40#[doc(alias = "..")]
41#[derive(#[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)]
42#[derive_const(#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[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 = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl crate::clone::Clone for RangeFull {
    #[inline]
    fn clone(&self) -> RangeFull { *self }
}Clone, #[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl crate::default::Default for RangeFull {
    #[inline]
    fn default() -> RangeFull { RangeFull {} }
}Default, #[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl crate::cmp::Eq for RangeFull {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}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 = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl crate::cmp::PartialEq for RangeFull {
    #[inline]
    fn eq(&self, other: &RangeFull) -> bool { true }
}PartialEq)]
43#[stable(feature = "rust1", since = "1.0.0")]
44pub struct RangeFull;
45
46#[stable(feature = "rust1", since = "1.0.0")]
47impl fmt::Debug for RangeFull {
48    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
49        fmt.write_fmt(format_args!(".."))write!(fmt, "..")
50    }
51}
52
53/// A (half-open) range bounded inclusively below and exclusively above
54/// (`start..end`).
55///
56/// The range `start..end` contains all values with `start <= x < end`.
57/// It is empty if `start >= end`.
58///
59/// # Examples
60///
61/// The `start..end` syntax is a `Range`:
62///
63/// ```
64/// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
65/// assert_eq!(3 + 4 + 5, (3..6).sum());
66/// ```
67///
68/// ```
69/// let arr = [0, 1, 2, 3, 4];
70/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
71/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
72/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
73/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
74/// assert_eq!(arr[1.. 3], [   1, 2      ]); // This is a `Range`
75/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
76/// ```
77#[lang = "Range"]
78#[doc(alias = "..")]
79#[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)]
80#[derive_const(#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl<Idx: [const] crate::clone::Clone> crate::clone::Clone for
    Range<Idx> {
    #[inline]
    fn clone(&self) -> Range<Idx> {
        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 = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl<Idx: [const] crate::default::Default> crate::default::Default for
    Range<Idx> {
    #[inline]
    fn default() -> Range<Idx> {
        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 = "118304")]
#[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: &Range<Idx>) -> bool {
        self.start == other.start && self.end == other.end
    }
}PartialEq)] // not Copy -- see #27186
81#[stable(feature = "rust1", since = "1.0.0")]
82pub struct Range<Idx> {
83    /// The lower bound of the range (inclusive).
84    #[stable(feature = "rust1", since = "1.0.0")]
85    pub start: Idx,
86    /// The upper bound of the range (exclusive).
87    #[stable(feature = "rust1", since = "1.0.0")]
88    pub end: Idx,
89}
90
91#[stable(feature = "rust1", since = "1.0.0")]
92impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
93    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
94        self.start.fmt(fmt)?;
95        fmt.write_fmt(format_args!(".."))write!(fmt, "..")?;
96        self.end.fmt(fmt)?;
97        Ok(())
98    }
99}
100
101impl<Idx: PartialOrd<Idx>> Range<Idx> {
102    /// Returns `true` if `item` is contained in the range.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// assert!(!(3..5).contains(&2));
108    /// assert!( (3..5).contains(&3));
109    /// assert!( (3..5).contains(&4));
110    /// assert!(!(3..5).contains(&5));
111    ///
112    /// assert!(!(3..3).contains(&3));
113    /// assert!(!(3..2).contains(&3));
114    ///
115    /// assert!( (0.0..1.0).contains(&0.5));
116    /// assert!(!(0.0..1.0).contains(&f32::NAN));
117    /// assert!(!(0.0..f32::NAN).contains(&0.5));
118    /// assert!(!(f32::NAN..1.0).contains(&0.5));
119    /// ```
120    #[inline]
121    #[stable(feature = "range_contains", since = "1.35.0")]
122    #[rustc_const_unstable(feature = "const_range", issue = "none")]
123    pub const fn contains<U>(&self, item: &U) -> bool
124    where
125        Idx: [const] PartialOrd<U>,
126        U: ?Sized + [const] PartialOrd<Idx>,
127    {
128        <Self as RangeBounds<Idx>>::contains(self, item)
129    }
130
131    /// Returns `true` if the range contains no items.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// assert!(!(3..5).is_empty());
137    /// assert!( (3..3).is_empty());
138    /// assert!( (3..2).is_empty());
139    /// ```
140    ///
141    /// The range is empty if either side is incomparable:
142    ///
143    /// ```
144    /// assert!(!(3.0..5.0).is_empty());
145    /// assert!( (3.0..f32::NAN).is_empty());
146    /// assert!( (f32::NAN..5.0).is_empty());
147    /// ```
148    #[inline]
149    #[stable(feature = "range_is_empty", since = "1.47.0")]
150    #[rustc_const_unstable(feature = "const_range", issue = "none")]
151    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")]
152    pub const fn is_empty(&self) -> bool
153    where
154        Idx: [const] PartialOrd<Idx>,
155    {
156        !(self.start < self.end)
157    }
158}
159
160/// A range only bounded inclusively below (`start..`).
161///
162/// The `RangeFrom` `start..` contains all values with `x >= start`.
163///
164/// *Note*: Overflow in the [`Iterator`] implementation (when the contained
165/// data type reaches its numerical limit) is allowed to panic, wrap, or
166/// saturate. This behavior is defined by the implementation of the [`Step`]
167/// trait. For primitive integers, this follows the normal rules, and respects
168/// the overflow checks profile (panic in debug, wrap in release). Note also
169/// that overflow happens earlier than you might assume: the overflow happens
170/// in the call to `next` that yields the maximum value, as the range must be
171/// set to a state to yield the next value.
172///
173/// [`Step`]: crate::iter::Step
174///
175/// # Examples
176///
177/// The `start..` syntax is a `RangeFrom`:
178///
179/// ```
180/// assert_eq!((2..), std::ops::RangeFrom { start: 2 });
181/// assert_eq!(2 + 3 + 4, (2..).take(3).sum());
182/// ```
183///
184/// ```
185/// let arr = [0, 1, 2, 3, 4];
186/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
187/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
188/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
189/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]); // This is a `RangeFrom`
190/// assert_eq!(arr[1.. 3], [   1, 2      ]);
191/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
192/// ```
193#[lang = "RangeFrom"]
194#[doc(alias = "..")]
195#[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)]
196#[derive_const(#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl<Idx: [const] crate::clone::Clone> crate::clone::Clone for
    RangeFrom<Idx> {
    #[inline]
    fn clone(&self) -> RangeFrom<Idx> {
        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 = "118304")]
#[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: &RangeFrom<Idx>) -> bool { self.start == other.start }
}PartialEq)] // not Copy -- see #27186
197#[stable(feature = "rust1", since = "1.0.0")]
198pub struct RangeFrom<Idx> {
199    /// The lower bound of the range (inclusive).
200    #[stable(feature = "rust1", since = "1.0.0")]
201    pub start: Idx,
202}
203
204#[stable(feature = "rust1", since = "1.0.0")]
205impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
206    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
207        self.start.fmt(fmt)?;
208        fmt.write_fmt(format_args!(".."))write!(fmt, "..")?;
209        Ok(())
210    }
211}
212
213impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
214    /// Returns `true` if `item` is contained in the range.
215    ///
216    /// # Examples
217    ///
218    /// ```
219    /// assert!(!(3..).contains(&2));
220    /// assert!( (3..).contains(&3));
221    /// assert!( (3..).contains(&1_000_000_000));
222    ///
223    /// assert!( (0.0..).contains(&0.5));
224    /// assert!(!(0.0..).contains(&f32::NAN));
225    /// assert!(!(f32::NAN..).contains(&0.5));
226    /// ```
227    #[inline]
228    #[stable(feature = "range_contains", since = "1.35.0")]
229    #[rustc_const_unstable(feature = "const_range", issue = "none")]
230    pub const fn contains<U>(&self, item: &U) -> bool
231    where
232        Idx: [const] PartialOrd<U>,
233        U: ?Sized + [const] PartialOrd<Idx>,
234    {
235        <Self as RangeBounds<Idx>>::contains(self, item)
236    }
237}
238
239/// A range only bounded exclusively above (`..end`).
240///
241/// The `RangeTo` `..end` contains all values with `x < end`.
242/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
243///
244/// # Examples
245///
246/// The `..end` syntax is a `RangeTo`:
247///
248/// ```
249/// assert_eq!((..5), std::ops::RangeTo { end: 5 });
250/// ```
251///
252/// It does not have an [`IntoIterator`] implementation, so you can't use it in
253/// a `for` loop directly. This won't compile:
254///
255/// ```compile_fail,E0277
256/// // error[E0277]: the trait bound `std::ops::RangeTo<{integer}>:
257/// // std::iter::Iterator` is not satisfied
258/// for i in ..5 {
259///     // ...
260/// }
261/// ```
262///
263/// When used as a [slicing index], `RangeTo` produces a slice of all array
264/// elements before the index indicated by `end`.
265///
266/// ```
267/// let arr = [0, 1, 2, 3, 4];
268/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
269/// assert_eq!(arr[ .. 3], [0, 1, 2      ]); // This is a `RangeTo`
270/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
271/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
272/// assert_eq!(arr[1.. 3], [   1, 2      ]);
273/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
274/// ```
275///
276/// [slicing index]: crate::slice::SliceIndex
277#[lang = "RangeTo"]
278#[doc(alias = "..")]
279#[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)]
280#[derive_const(#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "rust1", since = "1.0.0")]
const impl<Idx: [const] crate::clone::Clone> crate::clone::Clone for
    RangeTo<Idx> {
    #[inline]
    fn clone(&self) -> RangeTo<Idx> {
        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 = "118304")]
#[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: &RangeTo<Idx>) -> bool { self.end == other.end }
}PartialEq)]
281#[stable(feature = "rust1", since = "1.0.0")]
282pub struct RangeTo<Idx> {
283    /// The upper bound of the range (exclusive).
284    #[stable(feature = "rust1", since = "1.0.0")]
285    pub end: Idx,
286}
287
288#[stable(feature = "rust1", since = "1.0.0")]
289impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
290    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
291        fmt.write_fmt(format_args!(".."))write!(fmt, "..")?;
292        self.end.fmt(fmt)?;
293        Ok(())
294    }
295}
296
297impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
298    /// Returns `true` if `item` is contained in the range.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// assert!( (..5).contains(&-1_000_000_000));
304    /// assert!( (..5).contains(&4));
305    /// assert!(!(..5).contains(&5));
306    ///
307    /// assert!( (..1.0).contains(&0.5));
308    /// assert!(!(..1.0).contains(&f32::NAN));
309    /// assert!(!(..f32::NAN).contains(&0.5));
310    /// ```
311    #[inline]
312    #[stable(feature = "range_contains", since = "1.35.0")]
313    #[rustc_const_unstable(feature = "const_range", issue = "none")]
314    pub const fn contains<U>(&self, item: &U) -> bool
315    where
316        Idx: [const] PartialOrd<U>,
317        U: ?Sized + [const] PartialOrd<Idx>,
318    {
319        <Self as RangeBounds<Idx>>::contains(self, item)
320    }
321}
322
323/// A range bounded inclusively below and above (`start..=end`).
324///
325/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
326/// and `x <= end`. It is empty unless `start <= end`.
327///
328/// This iterator is [fused], but the specific values of `start` and `end` after
329/// iteration has finished are **unspecified** other than that [`.is_empty()`]
330/// will return `true` once no more values will be produced.
331///
332/// [fused]: crate::iter::FusedIterator
333/// [`.is_empty()`]: RangeInclusive::is_empty
334///
335/// # Examples
336///
337/// The `start..=end` syntax is a `RangeInclusive`:
338///
339/// ```
340/// assert_eq!((3..=5), std::ops::RangeInclusive::new(3, 5));
341/// assert_eq!(3 + 4 + 5, (3..=5).sum());
342/// ```
343///
344/// ```
345/// let arr = [0, 1, 2, 3, 4];
346/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
347/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
348/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
349/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
350/// assert_eq!(arr[1.. 3], [   1, 2      ]);
351/// assert_eq!(arr[1..=3], [   1, 2, 3   ]); // This is a `RangeInclusive`
352/// ```
353#[lang = "RangeInclusive"]
354#[doc(alias = "..=")]
355#[derive(#[automatically_derived]
#[stable(feature = "inclusive_range", since = "1.26.0")]
impl<Idx: crate::clone::Clone> crate::clone::Clone for RangeInclusive<Idx> {
    #[inline]
    fn clone(&self) -> RangeInclusive<Idx> {
        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)]
356#[derive_const(#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[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 = "118304")]
#[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: &RangeInclusive<Idx>) -> bool {
        self.exhausted == other.exhausted && self.start == other.start &&
            self.end == other.end
    }
}PartialEq)] // not Copy -- see #27186
357#[stable(feature = "inclusive_range", since = "1.26.0")]
358pub struct RangeInclusive<Idx> {
359    // Note that the fields here are not public to allow changing the
360    // representation in the future; in particular, while we could plausibly
361    // expose start/end, modifying them without changing (future/current)
362    // private fields may lead to incorrect behavior, so we don't want to
363    // support that mode.
364    pub(crate) start: Idx,
365    pub(crate) end: Idx,
366
367    // This field represents an overflow flag for either bound (start or end):
368    //  - `false` upon construction
369    //  - `false` when iteration has yielded an element and
370    //    neither bound has overflowed the valid range of `Idx`
371    //  - `true` when iteration has caused either bound to
372    //    overflow the valid range of `Idx`
373    //
374    // When this is true, `start` or `end` may be left in an unspecified state,
375    // often wrapping (modular arithmetic) around at the boundary of `Idx`.
376    //
377    // This is required to support PartialEq and Hash without a PartialOrd bound or specialization.
378    pub(crate) exhausted: bool,
379}
380
381impl<Idx> RangeInclusive<Idx> {
382    /// Creates a new inclusive range. Equivalent to writing `start..=end`.
383    ///
384    /// # Examples
385    ///
386    /// ```
387    /// use std::ops::RangeInclusive;
388    ///
389    /// assert_eq!(3..=5, RangeInclusive::new(3, 5));
390    /// ```
391    #[lang = "range_inclusive_new"]
392    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
393    #[inline]
394    #[rustc_promotable]
395    #[rustc_const_stable(feature = "const_range_new", since = "1.32.0")]
396    pub const fn new(start: Idx, end: Idx) -> Self {
397        Self { start, end, exhausted: false }
398    }
399
400    /// Returns the lower bound of the range (inclusive).
401    ///
402    /// When using an inclusive range for iteration, the values of `start()` and
403    /// [`end()`] are unspecified after the iteration ended. To determine
404    /// whether the inclusive range is empty, use the [`is_empty()`] method
405    /// instead of comparing `start() > end()`.
406    ///
407    /// Note: the value returned by this method is unspecified after the range
408    /// has been iterated to exhaustion.
409    ///
410    /// [`end()`]: RangeInclusive::end
411    /// [`is_empty()`]: RangeInclusive::is_empty
412    ///
413    /// # Examples
414    ///
415    /// ```
416    /// assert_eq!((3..=5).start(), &3);
417    /// ```
418    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
419    #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
420    #[inline]
421    pub const fn start(&self) -> &Idx {
422        &self.start
423    }
424
425    /// Returns the upper bound of the range (inclusive).
426    ///
427    /// When using an inclusive range for iteration, the values of [`start()`]
428    /// and `end()` are unspecified after the iteration ended. To determine
429    /// whether the inclusive range is empty, use the [`is_empty()`] method
430    /// instead of comparing `start() > end()`.
431    ///
432    /// Note: the value returned by this method is unspecified after the range
433    /// has been iterated to exhaustion.
434    ///
435    /// [`start()`]: RangeInclusive::start
436    /// [`is_empty()`]: RangeInclusive::is_empty
437    ///
438    /// # Examples
439    ///
440    /// ```
441    /// assert_eq!((3..=5).end(), &5);
442    /// ```
443    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
444    #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
445    #[inline]
446    pub const fn end(&self) -> &Idx {
447        &self.end
448    }
449
450    /// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
451    ///
452    /// Note: the value returned by this method is unspecified after the range
453    /// has been iterated to exhaustion.
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// assert_eq!((3..=5).into_inner(), (3, 5));
459    /// ```
460    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
461    #[inline]
462    #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")]
463    pub const fn into_inner(self) -> (Idx, Idx) {
464        (self.start, self.end)
465    }
466}
467
468impl RangeInclusive<usize> {
469    /// Converts to an exclusive `Range` for `SliceIndex` implementations.
470    /// The caller is responsible for dealing with `end == usize::MAX`.
471    #[inline]
472    pub(crate) const fn into_slice_range(self) -> Range<usize> {
473        // Typically users should not be indexing with exhausted instances,
474        // but this heuristic should apply to most cases. This doesn't
475        // handle reverse iteration well (`next_back` and `nth_back` can
476        // cause `end` to wrap around to values at or near `usize::MAX`),
477        // but using an exhausted `RangeInclusive` after reverse iteration
478        // is an exceedingly rare case.
479
480        // If we're not exhausted, we want to simply slice `start..end + 1`.
481        // If we are exhausted, then slicing with `end + 1..end + 1` gives us an
482        // empty range that is still subject to bounds-checks for that endpoint.
483        let exclusive_end = self.end + 1;
484        let start = if self.exhausted { exclusive_end } else { self.start };
485        start..exclusive_end
486    }
487}
488
489#[stable(feature = "inclusive_range", since = "1.26.0")]
490impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
491    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
492        self.start.fmt(fmt)?;
493        fmt.write_fmt(format_args!("..="))write!(fmt, "..=")?;
494        self.end.fmt(fmt)?;
495        if self.exhausted {
496            fmt.write_fmt(format_args!(" (exhausted)"))write!(fmt, " (exhausted)")?;
497        }
498        Ok(())
499    }
500}
501
502impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
503    /// Returns `true` if `item` is contained in the range.
504    ///
505    /// # Examples
506    ///
507    /// ```
508    /// assert!(!(3..=5).contains(&2));
509    /// assert!( (3..=5).contains(&3));
510    /// assert!( (3..=5).contains(&4));
511    /// assert!( (3..=5).contains(&5));
512    /// assert!(!(3..=5).contains(&6));
513    ///
514    /// assert!( (3..=3).contains(&3));
515    /// assert!(!(3..=2).contains(&3));
516    ///
517    /// assert!( (0.0..=1.0).contains(&1.0));
518    /// assert!(!(0.0..=1.0).contains(&f32::NAN));
519    /// assert!(!(0.0..=f32::NAN).contains(&0.0));
520    /// assert!(!(f32::NAN..=1.0).contains(&1.0));
521    /// ```
522    ///
523    /// This method always returns `false` after iteration has finished:
524    ///
525    /// ```
526    /// let mut r = 3..=5;
527    /// assert!(r.contains(&3) && r.contains(&5));
528    /// for _ in r.by_ref() {}
529    /// // Precise field values are unspecified here
530    /// assert!(!r.contains(&3) && !r.contains(&5));
531    /// ```
532    #[inline]
533    #[stable(feature = "range_contains", since = "1.35.0")]
534    #[rustc_const_unstable(feature = "const_range", issue = "none")]
535    pub const fn contains<U>(&self, item: &U) -> bool
536    where
537        Idx: [const] PartialOrd<U>,
538        U: ?Sized + [const] PartialOrd<Idx>,
539    {
540        <Self as RangeBounds<Idx>>::contains(self, item)
541    }
542
543    /// Returns `true` if the range contains no items.
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// assert!(!(3..=5).is_empty());
549    /// assert!(!(3..=3).is_empty());
550    /// assert!( (3..=2).is_empty());
551    /// ```
552    ///
553    /// The range is empty if either side is incomparable:
554    ///
555    /// ```
556    /// assert!(!(3.0..=5.0).is_empty());
557    /// assert!( (3.0..=f32::NAN).is_empty());
558    /// assert!( (f32::NAN..=5.0).is_empty());
559    /// ```
560    ///
561    /// This method returns `true` after iteration has finished:
562    ///
563    /// ```
564    /// let mut r = 3..=5;
565    /// for _ in r.by_ref() {}
566    /// // Precise field values are unspecified here
567    /// assert!(r.is_empty());
568    /// ```
569    #[stable(feature = "range_is_empty", since = "1.47.0")]
570    #[inline]
571    #[rustc_const_unstable(feature = "const_range", issue = "none")]
572    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")]
573    pub const fn is_empty(&self) -> bool
574    where
575        Idx: [const] PartialOrd,
576    {
577        self.exhausted || !(self.start <= self.end)
578    }
579}
580
581/// A range only bounded inclusively above (`..=end`).
582///
583/// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
584/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
585///
586/// # Examples
587///
588/// The `..=end` syntax is a `RangeToInclusive`:
589///
590/// ```
591/// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
592/// ```
593///
594/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
595/// `for` loop directly. This won't compile:
596///
597/// ```compile_fail,E0277
598/// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
599/// // std::iter::Iterator` is not satisfied
600/// for i in ..=5 {
601///     // ...
602/// }
603/// ```
604///
605/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
606/// array elements up to and including the index indicated by `end`.
607///
608/// ```
609/// let arr = [0, 1, 2, 3, 4];
610/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
611/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
612/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]); // This is a `RangeToInclusive`
613/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
614/// assert_eq!(arr[1.. 3], [   1, 2      ]);
615/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
616/// ```
617///
618/// [slicing index]: crate::slice::SliceIndex
619#[lang = "RangeToInclusive"]
620#[doc(alias = "..=")]
621#[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)]
622#[derive(#[automatically_derived]
#[stable(feature = "inclusive_range", since = "1.26.0")]
impl<Idx: crate::clone::Clone> crate::clone::Clone for RangeToInclusive<Idx> {
    #[inline]
    fn clone(&self) -> RangeToInclusive<Idx> {
        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: &RangeToInclusive<Idx>) -> 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)]
623#[stable(feature = "inclusive_range", since = "1.26.0")]
624pub struct RangeToInclusive<Idx> {
625    /// The upper bound of the range (inclusive)
626    #[stable(feature = "inclusive_range", since = "1.26.0")]
627    pub end: Idx,
628}
629
630#[stable(feature = "inclusive_range", since = "1.26.0")]
631impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
632    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
633        fmt.write_fmt(format_args!("..="))write!(fmt, "..=")?;
634        self.end.fmt(fmt)?;
635        Ok(())
636    }
637}
638
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#[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]
    fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
        match self {
            Bound::Included(__self_0) =>
                crate::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Included", &__self_0),
            Bound::Excluded(__self_0) =>
                crate::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Excluded", &__self_0),
            Bound::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) {
        let __self_discr = crate::intrinsics::discriminant_value(self);
        crate::hash::Hash::hash(&__self_discr, state);
        match self {
            Bound::Included(__self_0) =>
                crate::hash::Hash::hash(__self_0, state),
            Bound::Excluded(__self_0) =>
                crate::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash)]
705#[derive_const(#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "collections_bound", since = "1.17.0")]
const impl<T: [const] crate::clone::Clone> crate::clone::Clone for Bound<T> {
    #[inline]
    fn clone(&self) -> Bound<T> {
        match self {
            Bound::Included(__self_0) =>
                Bound::Included(crate::clone::Clone::clone(__self_0)),
            Bound::Excluded(__self_0) =>
                Bound::Excluded(crate::clone::Clone::clone(__self_0)),
            Bound::Unbounded => Bound::Unbounded,
        }
    }
}Clone, #[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[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 = "118304")]
#[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: &Bound<T>) -> bool {
        let __self_discr = crate::intrinsics::discriminant_value(self);
        let __arg1_discr = crate::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Bound::Included(__self_0), Bound::Included(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Bound::Excluded(__self_0), Bound::Excluded(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}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 const 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    fn is_empty(&self) -> bool
951    where
952        T: [const] PartialOrd,
953    {
954        !match (self.start_bound(), self.end_bound()) {
955            (Unbounded, _) | (_, Unbounded) => true,
956            (Included(start), Excluded(end))
957            | (Excluded(start), Included(end))
958            | (Excluded(start), Excluded(end)) => start < end,
959            (Included(start), Included(end)) => start <= end,
960        }
961    }
962}
963
964/// Used to convert a range into start and end bounds, consuming the
965/// range by value.
966///
967/// `IntoBounds` is implemented by Rust’s built-in range types, produced
968/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
969#[unstable(feature = "range_into_bounds", issue = "136903")]
970#[rustc_const_unstable(feature = "const_range", issue = "none")]
971pub const trait IntoBounds<T>: [const] RangeBounds<T> {
972    /// Convert this range into the start and end bounds.
973    /// Returns `(start_bound, end_bound)`.
974    ///
975    /// # Examples
976    ///
977    /// ```
978    /// #![feature(range_into_bounds)]
979    /// use std::ops::Bound::*;
980    /// use std::ops::IntoBounds;
981    ///
982    /// assert_eq!((0..5).into_bounds(), (Included(0), Excluded(5)));
983    /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7)));
984    /// ```
985    fn into_bounds(self) -> (Bound<T>, Bound<T>);
986
987    /// Compute the intersection of  `self` and `other`.
988    ///
989    /// # Examples
990    ///
991    /// ```
992    /// #![feature(range_into_bounds)]
993    /// use std::ops::Bound::*;
994    /// use std::ops::IntoBounds;
995    ///
996    /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5)));
997    /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256)));
998    /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5)));
999    /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9)));
1000    /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13)));
1001    /// ```
1002    ///
1003    /// Combine with `is_empty` to determine if two ranges overlap.
1004    ///
1005    /// ```
1006    /// #![feature(range_into_bounds)]
1007    /// #![feature(range_bounds_is_empty)]
1008    /// use std::ops::{RangeBounds, IntoBounds};
1009    ///
1010    /// assert!(!(3..).intersect(..5).is_empty());
1011    /// assert!(!(-12..387).intersect(0..256).is_empty());
1012    /// assert!((1..5).intersect(6..).is_empty());
1013    /// ```
1014    fn intersect<R>(self, other: R) -> (Bound<T>, Bound<T>)
1015    where
1016        Self: Sized,
1017        T: [const] Ord + [const] Destruct,
1018        R: Sized + [const] IntoBounds<T>,
1019    {
1020        let (self_start, self_end) = IntoBounds::into_bounds(self);
1021        let (other_start, other_end) = IntoBounds::into_bounds(other);
1022
1023        let start = match (self_start, other_start) {
1024            (Included(a), Included(b)) => Included(Ord::max(a, b)),
1025            (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)),
1026            (Unbounded, Unbounded) => Unbounded,
1027
1028            (x, Unbounded) | (Unbounded, x) => x,
1029
1030            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1031                if i > e {
1032                    Included(i)
1033                } else {
1034                    Excluded(e)
1035                }
1036            }
1037        };
1038        let end = match (self_end, other_end) {
1039            (Included(a), Included(b)) => Included(Ord::min(a, b)),
1040            (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)),
1041            (Unbounded, Unbounded) => Unbounded,
1042
1043            (x, Unbounded) | (Unbounded, x) => x,
1044
1045            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1046                if i < e {
1047                    Included(i)
1048                } else {
1049                    Excluded(e)
1050                }
1051            }
1052        };
1053
1054        (start, end)
1055    }
1056}
1057
1058use self::Bound::{Excluded, Included, Unbounded};
1059
1060#[stable(feature = "collections_range", since = "1.28.0")]
1061#[rustc_const_unstable(feature = "const_range", issue = "none")]
1062const impl<T: ?Sized> RangeBounds<T> for RangeFull {
1063    fn start_bound(&self) -> Bound<&T> {
1064        Unbounded
1065    }
1066    fn end_bound(&self) -> Bound<&T> {
1067        Unbounded
1068    }
1069}
1070
1071#[unstable(feature = "range_into_bounds", issue = "136903")]
1072#[rustc_const_unstable(feature = "const_range", issue = "none")]
1073const impl<T> IntoBounds<T> for RangeFull {
1074    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1075        (Unbounded, Unbounded)
1076    }
1077}
1078
1079#[stable(feature = "collections_range", since = "1.28.0")]
1080#[rustc_const_unstable(feature = "const_range", issue = "none")]
1081const impl<T> RangeBounds<T> for RangeFrom<T> {
1082    fn start_bound(&self) -> Bound<&T> {
1083        Included(&self.start)
1084    }
1085    fn end_bound(&self) -> Bound<&T> {
1086        Unbounded
1087    }
1088}
1089
1090#[unstable(feature = "range_into_bounds", issue = "136903")]
1091#[rustc_const_unstable(feature = "const_range", issue = "none")]
1092const impl<T> IntoBounds<T> for RangeFrom<T> {
1093    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1094        (Included(self.start), Unbounded)
1095    }
1096}
1097
1098#[stable(feature = "collections_range", since = "1.28.0")]
1099#[rustc_const_unstable(feature = "const_range", issue = "none")]
1100const impl<T> RangeBounds<T> for RangeTo<T> {
1101    fn start_bound(&self) -> Bound<&T> {
1102        Unbounded
1103    }
1104    fn end_bound(&self) -> Bound<&T> {
1105        Excluded(&self.end)
1106    }
1107}
1108
1109#[unstable(feature = "range_into_bounds", issue = "136903")]
1110#[rustc_const_unstable(feature = "const_range", issue = "none")]
1111const impl<T> IntoBounds<T> for RangeTo<T> {
1112    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1113        (Unbounded, Excluded(self.end))
1114    }
1115}
1116
1117#[stable(feature = "collections_range", since = "1.28.0")]
1118#[rustc_const_unstable(feature = "const_range", issue = "none")]
1119const impl<T> RangeBounds<T> for Range<T> {
1120    fn start_bound(&self) -> Bound<&T> {
1121        Included(&self.start)
1122    }
1123    fn end_bound(&self) -> Bound<&T> {
1124        Excluded(&self.end)
1125    }
1126}
1127
1128#[unstable(feature = "range_into_bounds", issue = "136903")]
1129#[rustc_const_unstable(feature = "const_range", issue = "none")]
1130const impl<T> IntoBounds<T> for Range<T> {
1131    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1132        (Included(self.start), Excluded(self.end))
1133    }
1134}
1135
1136#[stable(feature = "collections_range", since = "1.28.0")]
1137#[rustc_const_unstable(feature = "const_range", issue = "none")]
1138const impl<T> RangeBounds<T> for RangeInclusive<T> {
1139    fn start_bound(&self) -> Bound<&T> {
1140        Included(&self.start)
1141    }
1142    fn end_bound(&self) -> Bound<&T> {
1143        if self.exhausted {
1144            // When the iterator is exhausted, it might have overflowed,
1145            // but we want the range to appear empty, containing nothing.
1146            // So in that case, we return bounds which are always empty:
1147            // Included(start)..Excluded(start)
1148            Excluded(&self.start)
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")]
1157const impl<T> IntoBounds<T> for RangeInclusive<T> {
1158    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1159        if !!self.exhausted {
    {
        crate::panicking::panic_fmt(format_args!("attempted to convert from an exhausted `RangeInclusive` (unspecified behavior)"));
    }
};assert!(
1160            !self.exhausted,
1161            "attempted to convert from an exhausted `RangeInclusive` (unspecified behavior)"
1162        );
1163
1164        (Included(self.start), Included(self.end))
1165    }
1166}
1167
1168#[stable(feature = "collections_range", since = "1.28.0")]
1169#[rustc_const_unstable(feature = "const_range", issue = "none")]
1170const impl<T> RangeBounds<T> for RangeToInclusive<T> {
1171    fn start_bound(&self) -> Bound<&T> {
1172        Unbounded
1173    }
1174    fn end_bound(&self) -> Bound<&T> {
1175        Included(&self.end)
1176    }
1177}
1178
1179#[unstable(feature = "range_into_bounds", issue = "136903")]
1180#[rustc_const_unstable(feature = "const_range", issue = "none")]
1181const impl<T> IntoBounds<T> for RangeToInclusive<T> {
1182    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1183        (Unbounded, Included(self.end))
1184    }
1185}
1186
1187#[stable(feature = "collections_range", since = "1.28.0")]
1188#[rustc_const_unstable(feature = "const_range", issue = "none")]
1189const impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
1190    fn start_bound(&self) -> Bound<&T> {
1191        match *self {
1192            (Included(ref start), _) => Included(start),
1193            (Excluded(ref start), _) => Excluded(start),
1194            (Unbounded, _) => Unbounded,
1195        }
1196    }
1197
1198    fn end_bound(&self) -> Bound<&T> {
1199        match *self {
1200            (_, Included(ref end)) => Included(end),
1201            (_, Excluded(ref end)) => Excluded(end),
1202            (_, Unbounded) => Unbounded,
1203        }
1204    }
1205}
1206
1207#[unstable(feature = "range_into_bounds", issue = "136903")]
1208#[rustc_const_unstable(feature = "const_range", issue = "none")]
1209const impl<T> IntoBounds<T> for (Bound<T>, Bound<T>) {
1210    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1211        self
1212    }
1213}
1214
1215#[stable(feature = "collections_range", since = "1.28.0")]
1216#[rustc_const_unstable(feature = "const_range", issue = "none")]
1217const impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
1218    fn start_bound(&self) -> Bound<&T> {
1219        self.0
1220    }
1221
1222    fn end_bound(&self) -> Bound<&T> {
1223        self.1
1224    }
1225}
1226
1227// This impl intentionally does not have `T: ?Sized`;
1228// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1229//
1230/// If you need to use this implementation where `T` is unsized,
1231/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1232/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`.
1233#[stable(feature = "collections_range", since = "1.28.0")]
1234#[rustc_const_unstable(feature = "const_range", issue = "none")]
1235const impl<T> RangeBounds<T> for RangeFrom<&T> {
1236    fn start_bound(&self) -> Bound<&T> {
1237        Included(self.start)
1238    }
1239    fn end_bound(&self) -> Bound<&T> {
1240        Unbounded
1241    }
1242}
1243
1244// This impl intentionally does not have `T: ?Sized`;
1245// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1246//
1247/// If you need to use this implementation where `T` is unsized,
1248/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1249/// i.e. replace `..end` with `(Bound::Unbounded, Bound::Excluded(end))`.
1250#[stable(feature = "collections_range", since = "1.28.0")]
1251#[rustc_const_unstable(feature = "const_range", issue = "none")]
1252const impl<T> RangeBounds<T> for RangeTo<&T> {
1253    fn start_bound(&self) -> Bound<&T> {
1254        Unbounded
1255    }
1256    fn end_bound(&self) -> Bound<&T> {
1257        Excluded(self.end)
1258    }
1259}
1260
1261// This impl intentionally does not have `T: ?Sized`;
1262// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1263//
1264/// If you need to use this implementation where `T` is unsized,
1265/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1266/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`.
1267#[stable(feature = "collections_range", since = "1.28.0")]
1268#[rustc_const_unstable(feature = "const_range", issue = "none")]
1269const impl<T> RangeBounds<T> for Range<&T> {
1270    fn start_bound(&self) -> Bound<&T> {
1271        Included(self.start)
1272    }
1273    fn end_bound(&self) -> Bound<&T> {
1274        Excluded(self.end)
1275    }
1276}
1277
1278// This impl intentionally does not have `T: ?Sized`;
1279// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1280//
1281/// If you need to use this implementation where `T` is unsized,
1282/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1283/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`.
1284#[stable(feature = "collections_range", since = "1.28.0")]
1285#[rustc_const_unstable(feature = "const_range", issue = "none")]
1286const impl<T> RangeBounds<T> for RangeInclusive<&T> {
1287    fn start_bound(&self) -> Bound<&T> {
1288        Included(self.start)
1289    }
1290    fn end_bound(&self) -> Bound<&T> {
1291        Included(self.end)
1292    }
1293}
1294
1295// This impl intentionally does not have `T: ?Sized`;
1296// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1297//
1298/// If you need to use this implementation where `T` is unsized,
1299/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1300/// i.e. replace `..=end` with `(Bound::Unbounded, Bound::Included(end))`.
1301#[stable(feature = "collections_range", since = "1.28.0")]
1302#[rustc_const_unstable(feature = "const_range", issue = "none")]
1303const impl<T> RangeBounds<T> for RangeToInclusive<&T> {
1304    fn start_bound(&self) -> Bound<&T> {
1305        Unbounded
1306    }
1307    fn end_bound(&self) -> Bound<&T> {
1308        Included(self.end)
1309    }
1310}
1311
1312/// An internal helper for `split_off` functions indicating
1313/// which end a `OneSidedRange` is bounded on.
1314#[unstable(feature = "one_sided_range", issue = "69780")]
1315#[allow(missing_debug_implementations)]
1316pub enum OneSidedRangeBound {
1317    /// The range is bounded inclusively from below and is unbounded above.
1318    StartInclusive,
1319    /// The range is bounded exclusively from above and is unbounded below.
1320    End,
1321    /// The range is bounded inclusively from above and is unbounded below.
1322    EndInclusive,
1323}
1324
1325/// `OneSidedRange` is implemented for built-in range types that are unbounded
1326/// on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`,
1327/// but `..`, `d..e`, and `f..=g` do not.
1328///
1329/// Types that implement `OneSidedRange<T>` must return `Bound::Unbounded`
1330/// from one of `RangeBounds::start_bound` or `RangeBounds::end_bound`.
1331#[unstable(feature = "one_sided_range", issue = "69780")]
1332#[rustc_const_unstable(feature = "const_range", issue = "none")]
1333pub const trait OneSidedRange<T>: RangeBounds<T> {
1334    /// An internal-only helper function for `split_off` and
1335    /// `split_off_mut` that returns the bound of the one-sided range.
1336    fn bound(self) -> (OneSidedRangeBound, T);
1337}
1338
1339#[unstable(feature = "one_sided_range", issue = "69780")]
1340#[rustc_const_unstable(feature = "const_range", issue = "none")]
1341const impl<T> OneSidedRange<T> for RangeTo<T>
1342where
1343    Self: RangeBounds<T>,
1344{
1345    fn bound(self) -> (OneSidedRangeBound, T) {
1346        (OneSidedRangeBound::End, self.end)
1347    }
1348}
1349
1350#[unstable(feature = "one_sided_range", issue = "69780")]
1351#[rustc_const_unstable(feature = "const_range", issue = "none")]
1352const impl<T> OneSidedRange<T> for RangeFrom<T>
1353where
1354    Self: RangeBounds<T>,
1355{
1356    fn bound(self) -> (OneSidedRangeBound, T) {
1357        (OneSidedRangeBound::StartInclusive, self.start)
1358    }
1359}
1360
1361#[unstable(feature = "one_sided_range", issue = "69780")]
1362#[rustc_const_unstable(feature = "const_range", issue = "none")]
1363const impl<T> OneSidedRange<T> for RangeToInclusive<T>
1364where
1365    Self: RangeBounds<T>,
1366{
1367    fn bound(self) -> (OneSidedRangeBound, T) {
1368        (OneSidedRangeBound::EndInclusive, self.end)
1369    }
1370}