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