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