]> git.lizzy.rs Git - rust.git/blob - library/core/src/ops/range.rs
Rollup merge of #75837 - GuillaumeGomez:fix-font-color-help-button, r=Cldfire
[rust.git] / library / core / src / ops / range.rs
1 use crate::fmt;
2 use crate::hash::Hash;
3
4 /// An unbounded range (`..`).
5 ///
6 /// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`.
7 /// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
8 ///
9 /// # Examples
10 ///
11 /// The `..` syntax is a `RangeFull`:
12 ///
13 /// ```
14 /// assert_eq!((..), std::ops::RangeFull);
15 /// ```
16 ///
17 /// It does not have an [`IntoIterator`] implementation, so you can't use it in
18 /// a `for` loop directly. This won't compile:
19 ///
20 /// ```compile_fail,E0277
21 /// for i in .. {
22 ///    // ...
23 /// }
24 /// ```
25 ///
26 /// Used as a [slicing index], `RangeFull` produces the full array as a slice.
27 ///
28 /// ```
29 /// let arr = [0, 1, 2, 3, 4];
30 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);  // RangeFull
31 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
32 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
33 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
34 /// assert_eq!(arr[1.. 3], [  1,2    ]);
35 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
36 /// ```
37 ///
38 /// [slicing index]: crate::slice::SliceIndex
39 #[cfg_attr(not(bootstrap), lang = "RangeFull")]
40 #[doc(alias = "..")]
41 #[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub struct RangeFull;
44
45 #[stable(feature = "rust1", since = "1.0.0")]
46 impl fmt::Debug for RangeFull {
47     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
48         write!(fmt, "..")
49     }
50 }
51
52 /// A (half-open) range bounded inclusively below and exclusively above
53 /// (`start..end`).
54 ///
55 /// The `Range` `start..end` contains all values with `x >= start` and
56 /// `x < end`. It is empty unless `start < end`.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
62 /// assert_eq!(3 + 4 + 5, (3..6).sum());
63 ///
64 /// let arr = [0, 1, 2, 3, 4];
65 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
66 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
67 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
68 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
69 /// assert_eq!(arr[1.. 3], [  1,2    ]);  // Range
70 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
71 /// ```
72 #[cfg_attr(not(bootstrap), lang = "Range")]
73 #[doc(alias = "..")]
74 #[derive(Clone, Default, PartialEq, Eq, Hash)] // not Copy -- see #27186
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub struct Range<Idx> {
77     /// The lower bound of the range (inclusive).
78     #[stable(feature = "rust1", since = "1.0.0")]
79     pub start: Idx,
80     /// The upper bound of the range (exclusive).
81     #[stable(feature = "rust1", since = "1.0.0")]
82     pub end: Idx,
83 }
84
85 #[stable(feature = "rust1", since = "1.0.0")]
86 impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
87     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
88         self.start.fmt(fmt)?;
89         write!(fmt, "..")?;
90         self.end.fmt(fmt)?;
91         Ok(())
92     }
93 }
94
95 impl<Idx: PartialOrd<Idx>> Range<Idx> {
96     /// Returns `true` if `item` is contained in the range.
97     ///
98     /// # Examples
99     ///
100     /// ```
101     /// assert!(!(3..5).contains(&2));
102     /// assert!( (3..5).contains(&3));
103     /// assert!( (3..5).contains(&4));
104     /// assert!(!(3..5).contains(&5));
105     ///
106     /// assert!(!(3..3).contains(&3));
107     /// assert!(!(3..2).contains(&3));
108     ///
109     /// assert!( (0.0..1.0).contains(&0.5));
110     /// assert!(!(0.0..1.0).contains(&f32::NAN));
111     /// assert!(!(0.0..f32::NAN).contains(&0.5));
112     /// assert!(!(f32::NAN..1.0).contains(&0.5));
113     /// ```
114     #[stable(feature = "range_contains", since = "1.35.0")]
115     pub fn contains<U>(&self, item: &U) -> bool
116     where
117         Idx: PartialOrd<U>,
118         U: ?Sized + PartialOrd<Idx>,
119     {
120         <Self as RangeBounds<Idx>>::contains(self, item)
121     }
122
123     /// Returns `true` if the range contains no items.
124     ///
125     /// # Examples
126     ///
127     /// ```
128     /// assert!(!(3..5).is_empty());
129     /// assert!( (3..3).is_empty());
130     /// assert!( (3..2).is_empty());
131     /// ```
132     ///
133     /// The range is empty if either side is incomparable:
134     ///
135     /// ```
136     /// assert!(!(3.0..5.0).is_empty());
137     /// assert!( (3.0..f32::NAN).is_empty());
138     /// assert!( (f32::NAN..5.0).is_empty());
139     /// ```
140     #[stable(feature = "range_is_empty", since = "1.47.0")]
141     pub fn is_empty(&self) -> bool {
142         !(self.start < self.end)
143     }
144 }
145
146 /// A range only bounded inclusively below (`start..`).
147 ///
148 /// The `RangeFrom` `start..` contains all values with `x >= start`.
149 ///
150 /// *Note*: Overflow in the [`Iterator`] implementation (when the contained
151 /// data type reaches its numerical limit) is allowed to panic, wrap, or
152 /// saturate. This behavior is defined by the implementation of the [`Step`]
153 /// trait. For primitive integers, this follows the normal rules, and respects
154 /// the overflow checks profile (panic in debug, wrap in release). Note also
155 /// that overflow happens earlier than you might assume: the overflow happens
156 /// in the call to `next` that yields the maximum value, as the range must be
157 /// set to a state to yield the next value.
158 ///
159 /// [`Step`]: crate::iter::Step
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// assert_eq!((2..), std::ops::RangeFrom { start: 2 });
165 /// assert_eq!(2 + 3 + 4, (2..).take(3).sum());
166 ///
167 /// let arr = [0, 1, 2, 3, 4];
168 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
169 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
170 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
171 /// assert_eq!(arr[1..  ], [  1,2,3,4]);  // RangeFrom
172 /// assert_eq!(arr[1.. 3], [  1,2    ]);
173 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
174 /// ```
175 #[cfg_attr(not(bootstrap), lang = "RangeFrom")]
176 #[doc(alias = "..")]
177 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
178 #[stable(feature = "rust1", since = "1.0.0")]
179 pub struct RangeFrom<Idx> {
180     /// The lower bound of the range (inclusive).
181     #[stable(feature = "rust1", since = "1.0.0")]
182     pub start: Idx,
183 }
184
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
187     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
188         self.start.fmt(fmt)?;
189         write!(fmt, "..")?;
190         Ok(())
191     }
192 }
193
194 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
195     /// Returns `true` if `item` is contained in the range.
196     ///
197     /// # Examples
198     ///
199     /// ```
200     /// assert!(!(3..).contains(&2));
201     /// assert!( (3..).contains(&3));
202     /// assert!( (3..).contains(&1_000_000_000));
203     ///
204     /// assert!( (0.0..).contains(&0.5));
205     /// assert!(!(0.0..).contains(&f32::NAN));
206     /// assert!(!(f32::NAN..).contains(&0.5));
207     /// ```
208     #[stable(feature = "range_contains", since = "1.35.0")]
209     pub fn contains<U>(&self, item: &U) -> bool
210     where
211         Idx: PartialOrd<U>,
212         U: ?Sized + PartialOrd<Idx>,
213     {
214         <Self as RangeBounds<Idx>>::contains(self, item)
215     }
216 }
217
218 /// A range only bounded exclusively above (`..end`).
219 ///
220 /// The `RangeTo` `..end` contains all values with `x < end`.
221 /// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
222 ///
223 /// # Examples
224 ///
225 /// The `..end` syntax is a `RangeTo`:
226 ///
227 /// ```
228 /// assert_eq!((..5), std::ops::RangeTo { end: 5 });
229 /// ```
230 ///
231 /// It does not have an [`IntoIterator`] implementation, so you can't use it in
232 /// a `for` loop directly. This won't compile:
233 ///
234 /// ```compile_fail,E0277
235 /// // error[E0277]: the trait bound `std::ops::RangeTo<{integer}>:
236 /// // std::iter::Iterator` is not satisfied
237 /// for i in ..5 {
238 ///     // ...
239 /// }
240 /// ```
241 ///
242 /// When used as a [slicing index], `RangeTo` produces a slice of all array
243 /// elements before the index indicated by `end`.
244 ///
245 /// ```
246 /// let arr = [0, 1, 2, 3, 4];
247 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
248 /// assert_eq!(arr[ .. 3], [0,1,2    ]);  // RangeTo
249 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
250 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
251 /// assert_eq!(arr[1.. 3], [  1,2    ]);
252 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
253 /// ```
254 ///
255 /// [slicing index]: crate::slice::SliceIndex
256 #[cfg_attr(not(bootstrap), lang = "RangeTo")]
257 #[doc(alias = "..")]
258 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub struct RangeTo<Idx> {
261     /// The upper bound of the range (exclusive).
262     #[stable(feature = "rust1", since = "1.0.0")]
263     pub end: Idx,
264 }
265
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
268     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
269         write!(fmt, "..")?;
270         self.end.fmt(fmt)?;
271         Ok(())
272     }
273 }
274
275 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
276     /// Returns `true` if `item` is contained in the range.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// assert!( (..5).contains(&-1_000_000_000));
282     /// assert!( (..5).contains(&4));
283     /// assert!(!(..5).contains(&5));
284     ///
285     /// assert!( (..1.0).contains(&0.5));
286     /// assert!(!(..1.0).contains(&f32::NAN));
287     /// assert!(!(..f32::NAN).contains(&0.5));
288     /// ```
289     #[stable(feature = "range_contains", since = "1.35.0")]
290     pub fn contains<U>(&self, item: &U) -> bool
291     where
292         Idx: PartialOrd<U>,
293         U: ?Sized + PartialOrd<Idx>,
294     {
295         <Self as RangeBounds<Idx>>::contains(self, item)
296     }
297 }
298
299 /// A range bounded inclusively below and above (`start..=end`).
300 ///
301 /// The `RangeInclusive` `start..=end` contains all values with `x >= start`
302 /// and `x <= end`. It is empty unless `start <= end`.
303 ///
304 /// This iterator is [fused], but the specific values of `start` and `end` after
305 /// iteration has finished are **unspecified** other than that [`.is_empty()`]
306 /// will return `true` once no more values will be produced.
307 ///
308 /// [fused]: crate::iter::FusedIterator
309 /// [`.is_empty()`]: RangeInclusive::is_empty
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// assert_eq!((3..=5), std::ops::RangeInclusive::new(3, 5));
315 /// assert_eq!(3 + 4 + 5, (3..=5).sum());
316 ///
317 /// let arr = [0, 1, 2, 3, 4];
318 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
319 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
320 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
321 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
322 /// assert_eq!(arr[1.. 3], [  1,2    ]);
323 /// assert_eq!(arr[1..=3], [  1,2,3  ]);  // RangeInclusive
324 /// ```
325 #[cfg_attr(not(bootstrap), lang = "RangeInclusive")]
326 #[doc(alias = "..=")]
327 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
328 #[stable(feature = "inclusive_range", since = "1.26.0")]
329 pub struct RangeInclusive<Idx> {
330     // Note that the fields here are not public to allow changing the
331     // representation in the future; in particular, while we could plausibly
332     // expose start/end, modifying them without changing (future/current)
333     // private fields may lead to incorrect behavior, so we don't want to
334     // support that mode.
335     pub(crate) start: Idx,
336     pub(crate) end: Idx,
337
338     // This field is:
339     //  - `false` upon construction
340     //  - `false` when iteration has yielded an element and the iterator is not exhausted
341     //  - `true` when iteration has been used to exhaust the iterator
342     //
343     // This is required to support PartialEq and Hash without a PartialOrd bound or specialization.
344     pub(crate) exhausted: bool,
345 }
346
347 impl<Idx> RangeInclusive<Idx> {
348     /// Creates a new inclusive range. Equivalent to writing `start..=end`.
349     ///
350     /// # Examples
351     ///
352     /// ```
353     /// use std::ops::RangeInclusive;
354     ///
355     /// assert_eq!(3..=5, RangeInclusive::new(3, 5));
356     /// ```
357     #[cfg_attr(not(bootstrap), lang = "range_inclusive_new")]
358     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
359     #[inline]
360     #[rustc_promotable]
361     #[rustc_const_stable(feature = "const_range_new", since = "1.32.0")]
362     pub const fn new(start: Idx, end: Idx) -> Self {
363         Self { start, end, exhausted: false }
364     }
365
366     /// Returns the lower bound of the range (inclusive).
367     ///
368     /// When using an inclusive range for iteration, the values of `start()` and
369     /// [`end()`] are unspecified after the iteration ended. To determine
370     /// whether the inclusive range is empty, use the [`is_empty()`] method
371     /// instead of comparing `start() > end()`.
372     ///
373     /// Note: the value returned by this method is unspecified after the range
374     /// has been iterated to exhaustion.
375     ///
376     /// [`end()`]: RangeInclusive::end
377     /// [`is_empty()`]: RangeInclusive::is_empty
378     ///
379     /// # Examples
380     ///
381     /// ```
382     /// assert_eq!((3..=5).start(), &3);
383     /// ```
384     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
385     #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
386     #[inline]
387     pub const fn start(&self) -> &Idx {
388         &self.start
389     }
390
391     /// Returns the upper bound of the range (inclusive).
392     ///
393     /// When using an inclusive range for iteration, the values of [`start()`]
394     /// and `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     /// [`start()`]: RangeInclusive::start
402     /// [`is_empty()`]: RangeInclusive::is_empty
403     ///
404     /// # Examples
405     ///
406     /// ```
407     /// assert_eq!((3..=5).end(), &5);
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 end(&self) -> &Idx {
413         &self.end
414     }
415
416     /// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
417     ///
418     /// Note: the value returned by this method is unspecified after the range
419     /// has been iterated to exhaustion.
420     ///
421     /// # Examples
422     ///
423     /// ```
424     /// assert_eq!((3..=5).into_inner(), (3, 5));
425     /// ```
426     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
427     #[inline]
428     pub fn into_inner(self) -> (Idx, Idx) {
429         (self.start, self.end)
430     }
431 }
432
433 #[stable(feature = "inclusive_range", since = "1.26.0")]
434 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
435     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
436         self.start.fmt(fmt)?;
437         write!(fmt, "..=")?;
438         self.end.fmt(fmt)?;
439         if self.exhausted {
440             write!(fmt, " (exhausted)")?;
441         }
442         Ok(())
443     }
444 }
445
446 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
447     /// Returns `true` if `item` is contained in the range.
448     ///
449     /// # Examples
450     ///
451     /// ```
452     /// assert!(!(3..=5).contains(&2));
453     /// assert!( (3..=5).contains(&3));
454     /// assert!( (3..=5).contains(&4));
455     /// assert!( (3..=5).contains(&5));
456     /// assert!(!(3..=5).contains(&6));
457     ///
458     /// assert!( (3..=3).contains(&3));
459     /// assert!(!(3..=2).contains(&3));
460     ///
461     /// assert!( (0.0..=1.0).contains(&1.0));
462     /// assert!(!(0.0..=1.0).contains(&f32::NAN));
463     /// assert!(!(0.0..=f32::NAN).contains(&0.0));
464     /// assert!(!(f32::NAN..=1.0).contains(&1.0));
465     /// ```
466     #[stable(feature = "range_contains", since = "1.35.0")]
467     pub fn contains<U>(&self, item: &U) -> bool
468     where
469         Idx: PartialOrd<U>,
470         U: ?Sized + PartialOrd<Idx>,
471     {
472         <Self as RangeBounds<Idx>>::contains(self, item)
473     }
474
475     /// Returns `true` if the range contains no items.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// assert!(!(3..=5).is_empty());
481     /// assert!(!(3..=3).is_empty());
482     /// assert!( (3..=2).is_empty());
483     /// ```
484     ///
485     /// The range is empty if either side is incomparable:
486     ///
487     /// ```
488     /// assert!(!(3.0..=5.0).is_empty());
489     /// assert!( (3.0..=f32::NAN).is_empty());
490     /// assert!( (f32::NAN..=5.0).is_empty());
491     /// ```
492     ///
493     /// This method returns `true` after iteration has finished:
494     ///
495     /// ```
496     /// let mut r = 3..=5;
497     /// for _ in r.by_ref() {}
498     /// // Precise field values are unspecified here
499     /// assert!(r.is_empty());
500     /// ```
501     #[stable(feature = "range_is_empty", since = "1.47.0")]
502     #[inline]
503     pub fn is_empty(&self) -> bool {
504         self.exhausted || !(self.start <= self.end)
505     }
506 }
507
508 /// A range only bounded inclusively above (`..=end`).
509 ///
510 /// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
511 /// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
512 ///
513 /// # Examples
514 ///
515 /// The `..=end` syntax is a `RangeToInclusive`:
516 ///
517 /// ```
518 /// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
519 /// ```
520 ///
521 /// It does not have an [`IntoIterator`] implementation, so you can't use it in a
522 /// `for` loop directly. This won't compile:
523 ///
524 /// ```compile_fail,E0277
525 /// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
526 /// // std::iter::Iterator` is not satisfied
527 /// for i in ..=5 {
528 ///     // ...
529 /// }
530 /// ```
531 ///
532 /// When used as a [slicing index], `RangeToInclusive` produces a slice of all
533 /// array elements up to and including the index indicated by `end`.
534 ///
535 /// ```
536 /// let arr = [0, 1, 2, 3, 4];
537 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
538 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
539 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);  // RangeToInclusive
540 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
541 /// assert_eq!(arr[1.. 3], [  1,2    ]);
542 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
543 /// ```
544 ///
545 /// [slicing index]: crate::slice::SliceIndex
546 #[cfg_attr(not(bootstrap), lang = "RangeToInclusive")]
547 #[doc(alias = "..=")]
548 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
549 #[stable(feature = "inclusive_range", since = "1.26.0")]
550 pub struct RangeToInclusive<Idx> {
551     /// The upper bound of the range (inclusive)
552     #[stable(feature = "inclusive_range", since = "1.26.0")]
553     pub end: Idx,
554 }
555
556 #[stable(feature = "inclusive_range", since = "1.26.0")]
557 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
558     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
559         write!(fmt, "..=")?;
560         self.end.fmt(fmt)?;
561         Ok(())
562     }
563 }
564
565 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
566     /// Returns `true` if `item` is contained in the range.
567     ///
568     /// # Examples
569     ///
570     /// ```
571     /// assert!( (..=5).contains(&-1_000_000_000));
572     /// assert!( (..=5).contains(&5));
573     /// assert!(!(..=5).contains(&6));
574     ///
575     /// assert!( (..=1.0).contains(&1.0));
576     /// assert!(!(..=1.0).contains(&f32::NAN));
577     /// assert!(!(..=f32::NAN).contains(&0.5));
578     /// ```
579     #[stable(feature = "range_contains", since = "1.35.0")]
580     pub fn contains<U>(&self, item: &U) -> bool
581     where
582         Idx: PartialOrd<U>,
583         U: ?Sized + PartialOrd<Idx>,
584     {
585         <Self as RangeBounds<Idx>>::contains(self, item)
586     }
587 }
588
589 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
590 // because underflow would be possible with (..0).into()
591
592 /// An endpoint of a range of keys.
593 ///
594 /// # Examples
595 ///
596 /// `Bound`s are range endpoints:
597 ///
598 /// ```
599 /// use std::ops::Bound::*;
600 /// use std::ops::RangeBounds;
601 ///
602 /// assert_eq!((..100).start_bound(), Unbounded);
603 /// assert_eq!((1..12).start_bound(), Included(&1));
604 /// assert_eq!((1..12).end_bound(), Excluded(&12));
605 /// ```
606 ///
607 /// Using a tuple of `Bound`s as an argument to [`BTreeMap::range`].
608 /// Note that in most cases, it's better to use range syntax (`1..5`) instead.
609 ///
610 /// ```
611 /// use std::collections::BTreeMap;
612 /// use std::ops::Bound::{Excluded, Included, Unbounded};
613 ///
614 /// let mut map = BTreeMap::new();
615 /// map.insert(3, "a");
616 /// map.insert(5, "b");
617 /// map.insert(8, "c");
618 ///
619 /// for (key, value) in map.range((Excluded(3), Included(8))) {
620 ///     println!("{}: {}", key, value);
621 /// }
622 ///
623 /// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());
624 /// ```
625 ///
626 /// [`BTreeMap::range`]: ../../std/collections/btree_map/struct.BTreeMap.html#method.range
627 #[stable(feature = "collections_bound", since = "1.17.0")]
628 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
629 pub enum Bound<T> {
630     /// An inclusive bound.
631     #[stable(feature = "collections_bound", since = "1.17.0")]
632     Included(#[stable(feature = "collections_bound", since = "1.17.0")] T),
633     /// An exclusive bound.
634     #[stable(feature = "collections_bound", since = "1.17.0")]
635     Excluded(#[stable(feature = "collections_bound", since = "1.17.0")] T),
636     /// An infinite endpoint. Indicates that there is no bound in this direction.
637     #[stable(feature = "collections_bound", since = "1.17.0")]
638     Unbounded,
639 }
640
641 impl<T: Clone> Bound<&T> {
642     /// Map a `Bound<&T>` to a `Bound<T>` by cloning the contents of the bound.
643     ///
644     /// # Examples
645     ///
646     /// ```
647     /// #![feature(bound_cloned)]
648     /// use std::ops::Bound::*;
649     /// use std::ops::RangeBounds;
650     ///
651     /// assert_eq!((1..12).start_bound(), Included(&1));
652     /// assert_eq!((1..12).start_bound().cloned(), Included(1));
653     /// ```
654     #[unstable(feature = "bound_cloned", issue = "61356")]
655     pub fn cloned(self) -> Bound<T> {
656         match self {
657             Bound::Unbounded => Bound::Unbounded,
658             Bound::Included(x) => Bound::Included(x.clone()),
659             Bound::Excluded(x) => Bound::Excluded(x.clone()),
660         }
661     }
662 }
663
664 #[stable(feature = "collections_range", since = "1.28.0")]
665 /// `RangeBounds` is implemented by Rust's built-in range types, produced
666 /// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
667 pub trait RangeBounds<T: ?Sized> {
668     /// Start index bound.
669     ///
670     /// Returns the start value as a `Bound`.
671     ///
672     /// # Examples
673     ///
674     /// ```
675     /// # fn main() {
676     /// use std::ops::Bound::*;
677     /// use std::ops::RangeBounds;
678     ///
679     /// assert_eq!((..10).start_bound(), Unbounded);
680     /// assert_eq!((3..10).start_bound(), Included(&3));
681     /// # }
682     /// ```
683     #[stable(feature = "collections_range", since = "1.28.0")]
684     fn start_bound(&self) -> Bound<&T>;
685
686     /// End index bound.
687     ///
688     /// Returns the end value as a `Bound`.
689     ///
690     /// # Examples
691     ///
692     /// ```
693     /// # fn main() {
694     /// use std::ops::Bound::*;
695     /// use std::ops::RangeBounds;
696     ///
697     /// assert_eq!((3..).end_bound(), Unbounded);
698     /// assert_eq!((3..10).end_bound(), Excluded(&10));
699     /// # }
700     /// ```
701     #[stable(feature = "collections_range", since = "1.28.0")]
702     fn end_bound(&self) -> Bound<&T>;
703
704     /// Returns `true` if `item` is contained in the range.
705     ///
706     /// # Examples
707     ///
708     /// ```
709     /// assert!( (3..5).contains(&4));
710     /// assert!(!(3..5).contains(&2));
711     ///
712     /// assert!( (0.0..1.0).contains(&0.5));
713     /// assert!(!(0.0..1.0).contains(&f32::NAN));
714     /// assert!(!(0.0..f32::NAN).contains(&0.5));
715     /// assert!(!(f32::NAN..1.0).contains(&0.5));
716     #[stable(feature = "range_contains", since = "1.35.0")]
717     fn contains<U>(&self, item: &U) -> bool
718     where
719         T: PartialOrd<U>,
720         U: ?Sized + PartialOrd<T>,
721     {
722         (match self.start_bound() {
723             Included(ref start) => *start <= item,
724             Excluded(ref start) => *start < item,
725             Unbounded => true,
726         }) && (match self.end_bound() {
727             Included(ref end) => item <= *end,
728             Excluded(ref end) => item < *end,
729             Unbounded => true,
730         })
731     }
732 }
733
734 use self::Bound::{Excluded, Included, Unbounded};
735
736 #[stable(feature = "collections_range", since = "1.28.0")]
737 impl<T: ?Sized> RangeBounds<T> for RangeFull {
738     fn start_bound(&self) -> Bound<&T> {
739         Unbounded
740     }
741     fn end_bound(&self) -> Bound<&T> {
742         Unbounded
743     }
744 }
745
746 #[stable(feature = "collections_range", since = "1.28.0")]
747 impl<T> RangeBounds<T> for RangeFrom<T> {
748     fn start_bound(&self) -> Bound<&T> {
749         Included(&self.start)
750     }
751     fn end_bound(&self) -> Bound<&T> {
752         Unbounded
753     }
754 }
755
756 #[stable(feature = "collections_range", since = "1.28.0")]
757 impl<T> RangeBounds<T> for RangeTo<T> {
758     fn start_bound(&self) -> Bound<&T> {
759         Unbounded
760     }
761     fn end_bound(&self) -> Bound<&T> {
762         Excluded(&self.end)
763     }
764 }
765
766 #[stable(feature = "collections_range", since = "1.28.0")]
767 impl<T> RangeBounds<T> for Range<T> {
768     fn start_bound(&self) -> Bound<&T> {
769         Included(&self.start)
770     }
771     fn end_bound(&self) -> Bound<&T> {
772         Excluded(&self.end)
773     }
774 }
775
776 #[stable(feature = "collections_range", since = "1.28.0")]
777 impl<T> RangeBounds<T> for RangeInclusive<T> {
778     fn start_bound(&self) -> Bound<&T> {
779         Included(&self.start)
780     }
781     fn end_bound(&self) -> Bound<&T> {
782         Included(&self.end)
783     }
784 }
785
786 #[stable(feature = "collections_range", since = "1.28.0")]
787 impl<T> RangeBounds<T> for RangeToInclusive<T> {
788     fn start_bound(&self) -> Bound<&T> {
789         Unbounded
790     }
791     fn end_bound(&self) -> Bound<&T> {
792         Included(&self.end)
793     }
794 }
795
796 #[stable(feature = "collections_range", since = "1.28.0")]
797 impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
798     fn start_bound(&self) -> Bound<&T> {
799         match *self {
800             (Included(ref start), _) => Included(start),
801             (Excluded(ref start), _) => Excluded(start),
802             (Unbounded, _) => Unbounded,
803         }
804     }
805
806     fn end_bound(&self) -> Bound<&T> {
807         match *self {
808             (_, Included(ref end)) => Included(end),
809             (_, Excluded(ref end)) => Excluded(end),
810             (_, Unbounded) => Unbounded,
811         }
812     }
813 }
814
815 #[stable(feature = "collections_range", since = "1.28.0")]
816 impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
817     fn start_bound(&self) -> Bound<&T> {
818         self.0
819     }
820
821     fn end_bound(&self) -> Bound<&T> {
822         self.1
823     }
824 }
825
826 #[stable(feature = "collections_range", since = "1.28.0")]
827 impl<T> RangeBounds<T> for RangeFrom<&T> {
828     fn start_bound(&self) -> Bound<&T> {
829         Included(self.start)
830     }
831     fn end_bound(&self) -> Bound<&T> {
832         Unbounded
833     }
834 }
835
836 #[stable(feature = "collections_range", since = "1.28.0")]
837 impl<T> RangeBounds<T> for RangeTo<&T> {
838     fn start_bound(&self) -> Bound<&T> {
839         Unbounded
840     }
841     fn end_bound(&self) -> Bound<&T> {
842         Excluded(self.end)
843     }
844 }
845
846 #[stable(feature = "collections_range", since = "1.28.0")]
847 impl<T> RangeBounds<T> for Range<&T> {
848     fn start_bound(&self) -> Bound<&T> {
849         Included(self.start)
850     }
851     fn end_bound(&self) -> Bound<&T> {
852         Excluded(self.end)
853     }
854 }
855
856 #[stable(feature = "collections_range", since = "1.28.0")]
857 impl<T> RangeBounds<T> for RangeInclusive<&T> {
858     fn start_bound(&self) -> Bound<&T> {
859         Included(self.start)
860     }
861     fn end_bound(&self) -> Bound<&T> {
862         Included(self.end)
863     }
864 }
865
866 #[stable(feature = "collections_range", since = "1.28.0")]
867 impl<T> RangeBounds<T> for RangeToInclusive<&T> {
868     fn start_bound(&self) -> Bound<&T> {
869         Unbounded
870     }
871     fn end_bound(&self) -> Bound<&T> {
872         Included(self.end)
873     }
874 }