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