core/ops/range.rs
1#[cfg(not(feature = "ferrocene_certified"))]
2use crate::fmt;
3#[cfg(not(feature = "ferrocene_certified"))]
4use crate::hash::Hash;
5#[cfg(not(feature = "ferrocene_certified"))]
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_certified"), derive(Copy, Hash))]
45#[cfg_attr(not(feature = "ferrocene_certified"), 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_certified"))]
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_certified"), derive(Eq, Hash))]
84#[cfg_attr(not(feature = "ferrocene_certified"), 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_certified"))]
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
106#[cfg(not(feature = "ferrocene_certified"))]
107impl<Idx: PartialOrd<Idx>> Range<Idx> {
108 /// Returns `true` if `item` is contained in the range.
109 ///
110 /// # Examples
111 ///
112 /// ```
113 /// assert!(!(3..5).contains(&2));
114 /// assert!( (3..5).contains(&3));
115 /// assert!( (3..5).contains(&4));
116 /// assert!(!(3..5).contains(&5));
117 ///
118 /// assert!(!(3..3).contains(&3));
119 /// assert!(!(3..2).contains(&3));
120 ///
121 /// assert!( (0.0..1.0).contains(&0.5));
122 /// assert!(!(0.0..1.0).contains(&f32::NAN));
123 /// assert!(!(0.0..f32::NAN).contains(&0.5));
124 /// assert!(!(f32::NAN..1.0).contains(&0.5));
125 /// ```
126 #[inline]
127 #[stable(feature = "range_contains", since = "1.35.0")]
128 #[rustc_const_unstable(feature = "const_range", issue = "none")]
129 pub const fn contains<U>(&self, item: &U) -> bool
130 where
131 Idx: [const] PartialOrd<U>,
132 U: ?Sized + [const] PartialOrd<Idx>,
133 {
134 <Self as RangeBounds<Idx>>::contains(self, item)
135 }
136
137 /// Returns `true` if the range contains no items.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// assert!(!(3..5).is_empty());
143 /// assert!( (3..3).is_empty());
144 /// assert!( (3..2).is_empty());
145 /// ```
146 ///
147 /// The range is empty if either side is incomparable:
148 ///
149 /// ```
150 /// assert!(!(3.0..5.0).is_empty());
151 /// assert!( (3.0..f32::NAN).is_empty());
152 /// assert!( (f32::NAN..5.0).is_empty());
153 /// ```
154 #[inline]
155 #[stable(feature = "range_is_empty", since = "1.47.0")]
156 #[rustc_const_unstable(feature = "const_range", issue = "none")]
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_certified"), derive(Eq, Hash))]
201#[cfg_attr(not(feature = "ferrocene_certified"), 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_certified"))]
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_certified"))]
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_certified"), derive(Copy, Eq, Hash))]
287#[cfg_attr(not(feature = "ferrocene_certified"), 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_certified"))]
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_certified"))]
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_certified"), derive(Clone, Hash))]
365#[cfg_attr(not(feature = "ferrocene_certified"), 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_certified"))]
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
500#[cfg(not(feature = "ferrocene_certified"))]
501impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
502 /// Returns `true` if `item` is contained in the range.
503 ///
504 /// # Examples
505 ///
506 /// ```
507 /// assert!(!(3..=5).contains(&2));
508 /// assert!( (3..=5).contains(&3));
509 /// assert!( (3..=5).contains(&4));
510 /// assert!( (3..=5).contains(&5));
511 /// assert!(!(3..=5).contains(&6));
512 ///
513 /// assert!( (3..=3).contains(&3));
514 /// assert!(!(3..=2).contains(&3));
515 ///
516 /// assert!( (0.0..=1.0).contains(&1.0));
517 /// assert!(!(0.0..=1.0).contains(&f32::NAN));
518 /// assert!(!(0.0..=f32::NAN).contains(&0.0));
519 /// assert!(!(f32::NAN..=1.0).contains(&1.0));
520 /// ```
521 ///
522 /// This method always returns `false` after iteration has finished:
523 ///
524 /// ```
525 /// let mut r = 3..=5;
526 /// assert!(r.contains(&3) && r.contains(&5));
527 /// for _ in r.by_ref() {}
528 /// // Precise field values are unspecified here
529 /// assert!(!r.contains(&3) && !r.contains(&5));
530 /// ```
531 #[inline]
532 #[stable(feature = "range_contains", since = "1.35.0")]
533 #[rustc_const_unstable(feature = "const_range", issue = "none")]
534 pub const fn contains<U>(&self, item: &U) -> bool
535 where
536 Idx: [const] PartialOrd<U>,
537 U: ?Sized + [const] PartialOrd<Idx>,
538 {
539 <Self as RangeBounds<Idx>>::contains(self, item)
540 }
541
542 /// Returns `true` if the range contains no items.
543 ///
544 /// # Examples
545 ///
546 /// ```
547 /// assert!(!(3..=5).is_empty());
548 /// assert!(!(3..=3).is_empty());
549 /// assert!( (3..=2).is_empty());
550 /// ```
551 ///
552 /// The range is empty if either side is incomparable:
553 ///
554 /// ```
555 /// assert!(!(3.0..=5.0).is_empty());
556 /// assert!( (3.0..=f32::NAN).is_empty());
557 /// assert!( (f32::NAN..=5.0).is_empty());
558 /// ```
559 ///
560 /// This method returns `true` after iteration has finished:
561 ///
562 /// ```
563 /// let mut r = 3..=5;
564 /// for _ in r.by_ref() {}
565 /// // Precise field values are unspecified here
566 /// assert!(r.is_empty());
567 /// ```
568 #[stable(feature = "range_is_empty", since = "1.47.0")]
569 #[inline]
570 #[rustc_const_unstable(feature = "const_range", issue = "none")]
571 pub const fn is_empty(&self) -> bool
572 where
573 Idx: [const] PartialOrd,
574 {
575 self.exhausted || !(self.start <= self.end)
576 }
577}
578
579/// A range only bounded inclusively above (`..=end`).
580///
581/// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
582/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
583///
584/// # Examples
585///
586/// The `..=end` syntax is a `RangeToInclusive`:
587///
588/// ```
589/// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
590/// ```
591///
592/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
593/// `for` loop directly. This won't compile:
594///
595/// ```compile_fail,E0277
596/// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
597/// // std::iter::Iterator` is not satisfied
598/// for i in ..=5 {
599/// // ...
600/// }
601/// ```
602///
603/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
604/// array elements up to and including the index indicated by `end`.
605///
606/// ```
607/// let arr = [0, 1, 2, 3, 4];
608/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
609/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
610/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); // This is a `RangeToInclusive`
611/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
612/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
613/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
614/// ```
615///
616/// [slicing index]: crate::slice::SliceIndex
617#[lang = "RangeToInclusive"]
618#[doc(alias = "..=")]
619#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Hash))]
620#[cfg_attr(not(feature = "ferrocene_certified"), derive(Clone, PartialEq, Eq))]
621#[stable(feature = "inclusive_range", since = "1.26.0")]
622pub struct RangeToInclusive<Idx> {
623 /// The upper bound of the range (inclusive)
624 #[stable(feature = "inclusive_range", since = "1.26.0")]
625 pub end: Idx,
626}
627
628#[stable(feature = "inclusive_range", since = "1.26.0")]
629#[cfg(not(feature = "ferrocene_certified"))]
630impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
631 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
632 write!(fmt, "..=")?;
633 self.end.fmt(fmt)?;
634 Ok(())
635 }
636}
637
638#[cfg(not(feature = "ferrocene_certified"))]
639impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
640 /// Returns `true` if `item` is contained in the range.
641 ///
642 /// # Examples
643 ///
644 /// ```
645 /// assert!( (..=5).contains(&-1_000_000_000));
646 /// assert!( (..=5).contains(&5));
647 /// assert!(!(..=5).contains(&6));
648 ///
649 /// assert!( (..=1.0).contains(&1.0));
650 /// assert!(!(..=1.0).contains(&f32::NAN));
651 /// assert!(!(..=f32::NAN).contains(&0.5));
652 /// ```
653 #[inline]
654 #[stable(feature = "range_contains", since = "1.35.0")]
655 #[rustc_const_unstable(feature = "const_range", issue = "none")]
656 pub const fn contains<U>(&self, item: &U) -> bool
657 where
658 Idx: [const] PartialOrd<U>,
659 U: ?Sized + [const] PartialOrd<Idx>,
660 {
661 <Self as RangeBounds<Idx>>::contains(self, item)
662 }
663}
664
665// RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
666// because underflow would be possible with (..0).into()
667
668/// An endpoint of a range of keys.
669///
670/// # Examples
671///
672/// `Bound`s are range endpoints:
673///
674/// ```
675/// use std::ops::Bound::*;
676/// use std::ops::RangeBounds;
677///
678/// assert_eq!((..100).start_bound(), Unbounded);
679/// assert_eq!((1..12).start_bound(), Included(&1));
680/// assert_eq!((1..12).end_bound(), Excluded(&12));
681/// ```
682///
683/// Using a tuple of `Bound`s as an argument to [`BTreeMap::range`].
684/// Note that in most cases, it's better to use range syntax (`1..5`) instead.
685///
686/// ```
687/// use std::collections::BTreeMap;
688/// use std::ops::Bound::{Excluded, Included, Unbounded};
689///
690/// let mut map = BTreeMap::new();
691/// map.insert(3, "a");
692/// map.insert(5, "b");
693/// map.insert(8, "c");
694///
695/// for (key, value) in map.range((Excluded(3), Included(8))) {
696/// println!("{key}: {value}");
697/// }
698///
699/// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());
700/// ```
701///
702/// [`BTreeMap::range`]: ../../std/collections/btree_map/struct.BTreeMap.html#method.range
703#[stable(feature = "collections_bound", since = "1.17.0")]
704#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Debug, Hash))]
705#[cfg_attr(not(feature = "ferrocene_certified"), derive_const(Clone, Eq, PartialEq))]
706pub enum Bound<T> {
707 /// An inclusive bound.
708 #[stable(feature = "collections_bound", since = "1.17.0")]
709 Included(#[stable(feature = "collections_bound", since = "1.17.0")] T),
710 /// An exclusive bound.
711 #[stable(feature = "collections_bound", since = "1.17.0")]
712 Excluded(#[stable(feature = "collections_bound", since = "1.17.0")] T),
713 /// An infinite endpoint. Indicates that there is no bound in this direction.
714 #[stable(feature = "collections_bound", since = "1.17.0")]
715 Unbounded,
716}
717
718impl<T> Bound<T> {
719 /// Converts from `&Bound<T>` to `Bound<&T>`.
720 #[inline]
721 #[stable(feature = "bound_as_ref_shared", since = "1.65.0")]
722 #[rustc_const_unstable(feature = "const_range", issue = "none")]
723 pub const fn as_ref(&self) -> Bound<&T> {
724 match *self {
725 Included(ref x) => Included(x),
726 Excluded(ref x) => Excluded(x),
727 Unbounded => Unbounded,
728 }
729 }
730
731 /// Converts from `&mut Bound<T>` to `Bound<&mut T>`.
732 #[inline]
733 #[unstable(feature = "bound_as_ref", issue = "80996")]
734 pub const fn as_mut(&mut self) -> Bound<&mut T> {
735 match *self {
736 Included(ref mut x) => Included(x),
737 Excluded(ref mut x) => Excluded(x),
738 Unbounded => Unbounded,
739 }
740 }
741
742 /// Maps a `Bound<T>` to a `Bound<U>` by applying a function to the contained value (including
743 /// both `Included` and `Excluded`), returning a `Bound` of the same kind.
744 ///
745 /// # Examples
746 ///
747 /// ```
748 /// use std::ops::Bound::*;
749 ///
750 /// let bound_string = Included("Hello, World!");
751 ///
752 /// assert_eq!(bound_string.map(|s| s.len()), Included(13));
753 /// ```
754 ///
755 /// ```
756 /// use std::ops::Bound;
757 /// use Bound::*;
758 ///
759 /// let unbounded_string: Bound<String> = Unbounded;
760 ///
761 /// assert_eq!(unbounded_string.map(|s| s.len()), Unbounded);
762 /// ```
763 #[inline]
764 #[stable(feature = "bound_map", since = "1.77.0")]
765 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Bound<U> {
766 match self {
767 Unbounded => Unbounded,
768 Included(x) => Included(f(x)),
769 Excluded(x) => Excluded(f(x)),
770 }
771 }
772}
773
774impl<T: Copy> Bound<&T> {
775 /// Map a `Bound<&T>` to a `Bound<T>` by copying the contents of the bound.
776 ///
777 /// # Examples
778 ///
779 /// ```
780 /// #![feature(bound_copied)]
781 ///
782 /// use std::ops::Bound::*;
783 /// use std::ops::RangeBounds;
784 ///
785 /// assert_eq!((1..12).start_bound(), Included(&1));
786 /// assert_eq!((1..12).start_bound().copied(), Included(1));
787 /// ```
788 #[unstable(feature = "bound_copied", issue = "145966")]
789 #[must_use]
790 pub fn copied(self) -> Bound<T> {
791 match self {
792 Bound::Unbounded => Bound::Unbounded,
793 Bound::Included(x) => Bound::Included(*x),
794 Bound::Excluded(x) => Bound::Excluded(*x),
795 }
796 }
797}
798
799impl<T: Clone> Bound<&T> {
800 /// Map a `Bound<&T>` to a `Bound<T>` by cloning the contents of the bound.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use std::ops::Bound::*;
806 /// use std::ops::RangeBounds;
807 ///
808 /// let a1 = String::from("a");
809 /// let (a2, a3, a4) = (a1.clone(), a1.clone(), a1.clone());
810 ///
811 /// assert_eq!(Included(&a1), (a2..).start_bound());
812 /// assert_eq!(Included(a3), (a4..).start_bound().cloned());
813 /// ```
814 #[must_use = "`self` will be dropped if the result is not used"]
815 #[stable(feature = "bound_cloned", since = "1.55.0")]
816 #[rustc_const_unstable(feature = "const_range", issue = "none")]
817 pub const fn cloned(self) -> Bound<T>
818 where
819 T: [const] Clone,
820 {
821 match self {
822 Bound::Unbounded => Bound::Unbounded,
823 Bound::Included(x) => Bound::Included(x.clone()),
824 Bound::Excluded(x) => Bound::Excluded(x.clone()),
825 }
826 }
827}
828
829/// `RangeBounds` is implemented by Rust's built-in range types, produced
830/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
831#[stable(feature = "collections_range", since = "1.28.0")]
832#[rustc_diagnostic_item = "RangeBounds"]
833#[const_trait]
834#[rustc_const_unstable(feature = "const_range", issue = "none")]
835pub trait RangeBounds<T: ?Sized> {
836 /// Start index bound.
837 ///
838 /// Returns the start value as a `Bound`.
839 ///
840 /// # Examples
841 ///
842 /// ```
843 /// use std::ops::Bound::*;
844 /// use std::ops::RangeBounds;
845 ///
846 /// assert_eq!((..10).start_bound(), Unbounded);
847 /// assert_eq!((3..10).start_bound(), Included(&3));
848 /// ```
849 #[stable(feature = "collections_range", since = "1.28.0")]
850 fn start_bound(&self) -> Bound<&T>;
851
852 /// End index bound.
853 ///
854 /// Returns the end value as a `Bound`.
855 ///
856 /// # Examples
857 ///
858 /// ```
859 /// use std::ops::Bound::*;
860 /// use std::ops::RangeBounds;
861 ///
862 /// assert_eq!((3..).end_bound(), Unbounded);
863 /// assert_eq!((3..10).end_bound(), Excluded(&10));
864 /// ```
865 #[stable(feature = "collections_range", since = "1.28.0")]
866 fn end_bound(&self) -> Bound<&T>;
867
868 /// Returns `true` if `item` is contained in the range.
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// assert!( (3..5).contains(&4));
874 /// assert!(!(3..5).contains(&2));
875 ///
876 /// assert!( (0.0..1.0).contains(&0.5));
877 /// assert!(!(0.0..1.0).contains(&f32::NAN));
878 /// assert!(!(0.0..f32::NAN).contains(&0.5));
879 /// assert!(!(f32::NAN..1.0).contains(&0.5));
880 /// ```
881 #[inline]
882 #[stable(feature = "range_contains", since = "1.35.0")]
883 #[cfg(not(feature = "ferrocene_certified"))]
884 fn contains<U>(&self, item: &U) -> bool
885 where
886 T: [const] PartialOrd<U>,
887 U: ?Sized + [const] PartialOrd<T>,
888 {
889 (match self.start_bound() {
890 Included(start) => start <= item,
891 Excluded(start) => start < item,
892 Unbounded => true,
893 }) && (match self.end_bound() {
894 Included(end) => item <= end,
895 Excluded(end) => item < end,
896 Unbounded => true,
897 })
898 }
899
900 /// Returns `true` if the range contains no items.
901 /// One-sided ranges (`RangeFrom`, etc) always return `false`.
902 ///
903 /// # Examples
904 ///
905 /// ```
906 /// #![feature(range_bounds_is_empty)]
907 /// use std::ops::RangeBounds;
908 ///
909 /// assert!(!(3..).is_empty());
910 /// assert!(!(..2).is_empty());
911 /// assert!(!RangeBounds::is_empty(&(3..5)));
912 /// assert!( RangeBounds::is_empty(&(3..3)));
913 /// assert!( RangeBounds::is_empty(&(3..2)));
914 /// ```
915 ///
916 /// The range is empty if either side is incomparable:
917 ///
918 /// ```
919 /// #![feature(range_bounds_is_empty)]
920 /// use std::ops::RangeBounds;
921 ///
922 /// assert!(!RangeBounds::is_empty(&(3.0..5.0)));
923 /// assert!( RangeBounds::is_empty(&(3.0..f32::NAN)));
924 /// assert!( RangeBounds::is_empty(&(f32::NAN..5.0)));
925 /// ```
926 ///
927 /// But never empty if either side is unbounded:
928 ///
929 /// ```
930 /// #![feature(range_bounds_is_empty)]
931 /// use std::ops::RangeBounds;
932 ///
933 /// assert!(!(..0).is_empty());
934 /// assert!(!(i32::MAX..).is_empty());
935 /// assert!(!RangeBounds::<u8>::is_empty(&(..)));
936 /// ```
937 ///
938 /// `(Excluded(a), Excluded(b))` is only empty if `a >= b`:
939 ///
940 /// ```
941 /// #![feature(range_bounds_is_empty)]
942 /// use std::ops::Bound::*;
943 /// use std::ops::RangeBounds;
944 ///
945 /// assert!(!(Excluded(1), Excluded(3)).is_empty());
946 /// assert!(!(Excluded(1), Excluded(2)).is_empty());
947 /// assert!( (Excluded(1), Excluded(1)).is_empty());
948 /// assert!( (Excluded(2), Excluded(1)).is_empty());
949 /// assert!( (Excluded(3), Excluded(1)).is_empty());
950 /// ```
951 #[unstable(feature = "range_bounds_is_empty", issue = "137300")]
952 #[cfg(not(feature = "ferrocene_certified"))]
953 fn is_empty(&self) -> bool
954 where
955 T: [const] PartialOrd,
956 {
957 !match (self.start_bound(), self.end_bound()) {
958 (Unbounded, _) | (_, Unbounded) => true,
959 (Included(start), Excluded(end))
960 | (Excluded(start), Included(end))
961 | (Excluded(start), Excluded(end)) => start < end,
962 (Included(start), Included(end)) => start <= end,
963 }
964 }
965}
966
967/// Used to convert a range into start and end bounds, consuming the
968/// range by value.
969///
970/// `IntoBounds` is implemented by Rust’s built-in range types, produced
971/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
972#[unstable(feature = "range_into_bounds", issue = "136903")]
973#[const_trait]
974#[rustc_const_unstable(feature = "const_range", issue = "none")]
975pub trait IntoBounds<T>: [const] RangeBounds<T> {
976 /// Convert this range into the start and end bounds.
977 /// Returns `(start_bound, end_bound)`.
978 ///
979 /// # Examples
980 ///
981 /// ```
982 /// #![feature(range_into_bounds)]
983 /// use std::ops::Bound::*;
984 /// use std::ops::IntoBounds;
985 ///
986 /// assert_eq!((0..5).into_bounds(), (Included(0), Excluded(5)));
987 /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7)));
988 /// ```
989 fn into_bounds(self) -> (Bound<T>, Bound<T>);
990
991 /// Compute the intersection of `self` and `other`.
992 ///
993 /// # Examples
994 ///
995 /// ```
996 /// #![feature(range_into_bounds)]
997 /// use std::ops::Bound::*;
998 /// use std::ops::IntoBounds;
999 ///
1000 /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5)));
1001 /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256)));
1002 /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5)));
1003 /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9)));
1004 /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13)));
1005 /// ```
1006 ///
1007 /// Combine with `is_empty` to determine if two ranges overlap.
1008 ///
1009 /// ```
1010 /// #![feature(range_into_bounds)]
1011 /// #![feature(range_bounds_is_empty)]
1012 /// use std::ops::{RangeBounds, IntoBounds};
1013 ///
1014 /// assert!(!(3..).intersect(..5).is_empty());
1015 /// assert!(!(-12..387).intersect(0..256).is_empty());
1016 /// assert!((1..5).intersect(6..).is_empty());
1017 /// ```
1018 #[cfg(not(feature = "ferrocene_certified"))]
1019 fn intersect<R>(self, other: R) -> (Bound<T>, Bound<T>)
1020 where
1021 Self: Sized,
1022 T: [const] Ord + [const] Destruct,
1023 R: Sized + [const] IntoBounds<T>,
1024 {
1025 let (self_start, self_end) = IntoBounds::into_bounds(self);
1026 let (other_start, other_end) = IntoBounds::into_bounds(other);
1027
1028 let start = match (self_start, other_start) {
1029 (Included(a), Included(b)) => Included(Ord::max(a, b)),
1030 (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)),
1031 (Unbounded, Unbounded) => Unbounded,
1032
1033 (x, Unbounded) | (Unbounded, x) => x,
1034
1035 (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1036 if i > e {
1037 Included(i)
1038 } else {
1039 Excluded(e)
1040 }
1041 }
1042 };
1043 let end = match (self_end, other_end) {
1044 (Included(a), Included(b)) => Included(Ord::min(a, b)),
1045 (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)),
1046 (Unbounded, Unbounded) => Unbounded,
1047
1048 (x, Unbounded) | (Unbounded, x) => x,
1049
1050 (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
1051 if i < e {
1052 Included(i)
1053 } else {
1054 Excluded(e)
1055 }
1056 }
1057 };
1058
1059 (start, end)
1060 }
1061}
1062
1063use self::Bound::{Excluded, Included, Unbounded};
1064
1065#[stable(feature = "collections_range", since = "1.28.0")]
1066#[rustc_const_unstable(feature = "const_range", issue = "none")]
1067impl<T: ?Sized> const RangeBounds<T> for RangeFull {
1068 fn start_bound(&self) -> Bound<&T> {
1069 Unbounded
1070 }
1071 fn end_bound(&self) -> Bound<&T> {
1072 Unbounded
1073 }
1074}
1075
1076#[unstable(feature = "range_into_bounds", issue = "136903")]
1077#[rustc_const_unstable(feature = "const_range", issue = "none")]
1078impl<T> const IntoBounds<T> for RangeFull {
1079 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1080 (Unbounded, Unbounded)
1081 }
1082}
1083
1084#[stable(feature = "collections_range", since = "1.28.0")]
1085#[rustc_const_unstable(feature = "const_range", issue = "none")]
1086impl<T> const RangeBounds<T> for RangeFrom<T> {
1087 fn start_bound(&self) -> Bound<&T> {
1088 Included(&self.start)
1089 }
1090 fn end_bound(&self) -> Bound<&T> {
1091 Unbounded
1092 }
1093}
1094
1095#[unstable(feature = "range_into_bounds", issue = "136903")]
1096#[rustc_const_unstable(feature = "const_range", issue = "none")]
1097impl<T> const IntoBounds<T> for RangeFrom<T> {
1098 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1099 (Included(self.start), Unbounded)
1100 }
1101}
1102
1103#[stable(feature = "collections_range", since = "1.28.0")]
1104#[rustc_const_unstable(feature = "const_range", issue = "none")]
1105impl<T> const RangeBounds<T> for RangeTo<T> {
1106 fn start_bound(&self) -> Bound<&T> {
1107 Unbounded
1108 }
1109 fn end_bound(&self) -> Bound<&T> {
1110 Excluded(&self.end)
1111 }
1112}
1113
1114#[unstable(feature = "range_into_bounds", issue = "136903")]
1115#[rustc_const_unstable(feature = "const_range", issue = "none")]
1116impl<T> const IntoBounds<T> for RangeTo<T> {
1117 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1118 (Unbounded, Excluded(self.end))
1119 }
1120}
1121
1122#[stable(feature = "collections_range", since = "1.28.0")]
1123#[rustc_const_unstable(feature = "const_range", issue = "none")]
1124impl<T> const RangeBounds<T> for Range<T> {
1125 fn start_bound(&self) -> Bound<&T> {
1126 Included(&self.start)
1127 }
1128 fn end_bound(&self) -> Bound<&T> {
1129 Excluded(&self.end)
1130 }
1131}
1132
1133#[unstable(feature = "range_into_bounds", issue = "136903")]
1134#[rustc_const_unstable(feature = "const_range", issue = "none")]
1135impl<T> const IntoBounds<T> for Range<T> {
1136 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1137 (Included(self.start), Excluded(self.end))
1138 }
1139}
1140
1141#[stable(feature = "collections_range", since = "1.28.0")]
1142#[rustc_const_unstable(feature = "const_range", issue = "none")]
1143impl<T> const RangeBounds<T> for RangeInclusive<T> {
1144 fn start_bound(&self) -> Bound<&T> {
1145 Included(&self.start)
1146 }
1147 fn end_bound(&self) -> Bound<&T> {
1148 if self.exhausted {
1149 // When the iterator is exhausted, we usually have start == end,
1150 // but we want the range to appear empty, containing nothing.
1151 Excluded(&self.end)
1152 } else {
1153 Included(&self.end)
1154 }
1155 }
1156}
1157
1158#[unstable(feature = "range_into_bounds", issue = "136903")]
1159#[rustc_const_unstable(feature = "const_range", issue = "none")]
1160impl<T> const IntoBounds<T> for RangeInclusive<T> {
1161 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1162 (
1163 Included(self.start),
1164 if self.exhausted {
1165 // When the iterator is exhausted, we usually have start == end,
1166 // but we want the range to appear empty, containing nothing.
1167 Excluded(self.end)
1168 } else {
1169 Included(self.end)
1170 },
1171 )
1172 }
1173}
1174
1175#[stable(feature = "collections_range", since = "1.28.0")]
1176#[rustc_const_unstable(feature = "const_range", issue = "none")]
1177impl<T> const RangeBounds<T> for RangeToInclusive<T> {
1178 fn start_bound(&self) -> Bound<&T> {
1179 Unbounded
1180 }
1181 fn end_bound(&self) -> Bound<&T> {
1182 Included(&self.end)
1183 }
1184}
1185
1186#[unstable(feature = "range_into_bounds", issue = "136903")]
1187#[rustc_const_unstable(feature = "const_range", issue = "none")]
1188impl<T> const IntoBounds<T> for RangeToInclusive<T> {
1189 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1190 (Unbounded, Included(self.end))
1191 }
1192}
1193
1194#[stable(feature = "collections_range", since = "1.28.0")]
1195#[rustc_const_unstable(feature = "const_range", issue = "none")]
1196impl<T> const RangeBounds<T> for (Bound<T>, Bound<T>) {
1197 fn start_bound(&self) -> Bound<&T> {
1198 match *self {
1199 (Included(ref start), _) => Included(start),
1200 (Excluded(ref start), _) => Excluded(start),
1201 (Unbounded, _) => Unbounded,
1202 }
1203 }
1204
1205 fn end_bound(&self) -> Bound<&T> {
1206 match *self {
1207 (_, Included(ref end)) => Included(end),
1208 (_, Excluded(ref end)) => Excluded(end),
1209 (_, Unbounded) => Unbounded,
1210 }
1211 }
1212}
1213
1214#[unstable(feature = "range_into_bounds", issue = "136903")]
1215#[rustc_const_unstable(feature = "const_range", issue = "none")]
1216impl<T> const IntoBounds<T> for (Bound<T>, Bound<T>) {
1217 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
1218 self
1219 }
1220}
1221
1222#[stable(feature = "collections_range", since = "1.28.0")]
1223#[rustc_const_unstable(feature = "const_range", issue = "none")]
1224#[cfg(not(feature = "ferrocene_certified"))]
1225impl<'a, T: ?Sized + 'a> const RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
1226 fn start_bound(&self) -> Bound<&T> {
1227 self.0
1228 }
1229
1230 fn end_bound(&self) -> Bound<&T> {
1231 self.1
1232 }
1233}
1234
1235// This impl intentionally does not have `T: ?Sized`;
1236// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1237//
1238/// If you need to use this implementation where `T` is unsized,
1239/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1240/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`.
1241#[stable(feature = "collections_range", since = "1.28.0")]
1242#[rustc_const_unstable(feature = "const_range", issue = "none")]
1243impl<T> const RangeBounds<T> for RangeFrom<&T> {
1244 fn start_bound(&self) -> Bound<&T> {
1245 Included(self.start)
1246 }
1247 fn end_bound(&self) -> Bound<&T> {
1248 Unbounded
1249 }
1250}
1251
1252// This impl intentionally does not have `T: ?Sized`;
1253// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1254//
1255/// If you need to use this implementation where `T` is unsized,
1256/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1257/// i.e. replace `..end` with `(Bound::Unbounded, Bound::Excluded(end))`.
1258#[stable(feature = "collections_range", since = "1.28.0")]
1259#[rustc_const_unstable(feature = "const_range", issue = "none")]
1260impl<T> const RangeBounds<T> for RangeTo<&T> {
1261 fn start_bound(&self) -> Bound<&T> {
1262 Unbounded
1263 }
1264 fn end_bound(&self) -> Bound<&T> {
1265 Excluded(self.end)
1266 }
1267}
1268
1269// This impl intentionally does not have `T: ?Sized`;
1270// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1271//
1272/// If you need to use this implementation where `T` is unsized,
1273/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1274/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`.
1275#[stable(feature = "collections_range", since = "1.28.0")]
1276#[rustc_const_unstable(feature = "const_range", issue = "none")]
1277impl<T> const RangeBounds<T> for Range<&T> {
1278 fn start_bound(&self) -> Bound<&T> {
1279 Included(self.start)
1280 }
1281 fn end_bound(&self) -> Bound<&T> {
1282 Excluded(self.end)
1283 }
1284}
1285
1286// This impl intentionally does not have `T: ?Sized`;
1287// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1288//
1289/// If you need to use this implementation where `T` is unsized,
1290/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1291/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`.
1292#[stable(feature = "collections_range", since = "1.28.0")]
1293#[rustc_const_unstable(feature = "const_range", issue = "none")]
1294impl<T> const RangeBounds<T> for RangeInclusive<&T> {
1295 fn start_bound(&self) -> Bound<&T> {
1296 Included(self.start)
1297 }
1298 fn end_bound(&self) -> Bound<&T> {
1299 Included(self.end)
1300 }
1301}
1302
1303// This impl intentionally does not have `T: ?Sized`;
1304// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
1305//
1306/// If you need to use this implementation where `T` is unsized,
1307/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
1308/// i.e. replace `..=end` with `(Bound::Unbounded, Bound::Included(end))`.
1309#[stable(feature = "collections_range", since = "1.28.0")]
1310#[rustc_const_unstable(feature = "const_range", issue = "none")]
1311impl<T> const RangeBounds<T> for RangeToInclusive<&T> {
1312 fn start_bound(&self) -> Bound<&T> {
1313 Unbounded
1314 }
1315 fn end_bound(&self) -> Bound<&T> {
1316 Included(self.end)
1317 }
1318}
1319
1320/// An internal helper for `split_off` functions indicating
1321/// which end a `OneSidedRange` is bounded on.
1322#[unstable(feature = "one_sided_range", issue = "69780")]
1323#[allow(missing_debug_implementations)]
1324pub enum OneSidedRangeBound {
1325 /// The range is bounded inclusively from below and is unbounded above.
1326 StartInclusive,
1327 /// The range is bounded exclusively from above and is unbounded below.
1328 End,
1329 /// The range is bounded inclusively from above and is unbounded below.
1330 EndInclusive,
1331}
1332
1333/// `OneSidedRange` is implemented for built-in range types that are unbounded
1334/// on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`,
1335/// but `..`, `d..e`, and `f..=g` do not.
1336///
1337/// Types that implement `OneSidedRange<T>` must return `Bound::Unbounded`
1338/// from one of `RangeBounds::start_bound` or `RangeBounds::end_bound`.
1339#[unstable(feature = "one_sided_range", issue = "69780")]
1340#[const_trait]
1341#[rustc_const_unstable(feature = "const_range", issue = "none")]
1342pub trait OneSidedRange<T>: RangeBounds<T> {
1343 /// An internal-only helper function for `split_off` and
1344 /// `split_off_mut` that returns the bound of the one-sided range.
1345 fn bound(self) -> (OneSidedRangeBound, T);
1346}
1347
1348#[unstable(feature = "one_sided_range", issue = "69780")]
1349#[rustc_const_unstable(feature = "const_range", issue = "none")]
1350impl<T> const OneSidedRange<T> for RangeTo<T>
1351where
1352 Self: RangeBounds<T>,
1353{
1354 fn bound(self) -> (OneSidedRangeBound, T) {
1355 (OneSidedRangeBound::End, self.end)
1356 }
1357}
1358
1359#[unstable(feature = "one_sided_range", issue = "69780")]
1360#[rustc_const_unstable(feature = "const_range", issue = "none")]
1361impl<T> const OneSidedRange<T> for RangeFrom<T>
1362where
1363 Self: RangeBounds<T>,
1364{
1365 fn bound(self) -> (OneSidedRangeBound, T) {
1366 (OneSidedRangeBound::StartInclusive, self.start)
1367 }
1368}
1369
1370#[unstable(feature = "one_sided_range", issue = "69780")]
1371#[rustc_const_unstable(feature = "const_range", issue = "none")]
1372impl<T> const OneSidedRange<T> for RangeToInclusive<T>
1373where
1374 Self: RangeBounds<T>,
1375{
1376 fn bound(self) -> (OneSidedRangeBound, T) {
1377 (OneSidedRangeBound::EndInclusive, self.end)
1378 }
1379}