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