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