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