]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/range.rs
a707f0cc0627acdd6c3cf404c0cb30e8380039b1
[rust.git] / src / libcore / ops / range.rs
1 use crate::fmt;
2 use crate::hash::{Hash, Hasher};
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 /// [`IntoIterator`]: ../iter/trait.Iterator.html
39 /// [`Iterator`]: ../iter/trait.IntoIterator.html
40 /// [slicing index]: ../slice/trait.SliceIndex.html
41 #[doc(alias = "..")]
42 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub struct RangeFull;
45
46 #[stable(feature = "rust1", since = "1.0.0")]
47 impl fmt::Debug for RangeFull {
48     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
49         write!(fmt, "..")
50     }
51 }
52
53 /// A (half-open) range bounded inclusively below and exclusively above
54 /// (`start..end`).
55 ///
56 /// The `Range` `start..end` contains all values with `x >= start` and
57 /// `x < end`. It is empty unless `start < end`.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
63 /// assert_eq!(3 + 4 + 5, (3..6).sum());
64 ///
65 /// let arr = [0, 1, 2, 3, 4];
66 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
67 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
68 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
69 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
70 /// assert_eq!(arr[1.. 3], [  1,2    ]);  // Range
71 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
72 /// ```
73 #[doc(alias = "..")]
74 #[derive(Clone, 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     /// use std::f32;
102     ///
103     /// assert!(!(3..5).contains(&2));
104     /// assert!( (3..5).contains(&3));
105     /// assert!( (3..5).contains(&4));
106     /// assert!(!(3..5).contains(&5));
107     ///
108     /// assert!(!(3..3).contains(&3));
109     /// assert!(!(3..2).contains(&3));
110     ///
111     /// assert!( (0.0..1.0).contains(&0.5));
112     /// assert!(!(0.0..1.0).contains(&f32::NAN));
113     /// assert!(!(0.0..f32::NAN).contains(&0.5));
114     /// assert!(!(f32::NAN..1.0).contains(&0.5));
115     /// ```
116     #[stable(feature = "range_contains", since = "1.35.0")]
117     pub fn contains<U>(&self, item: &U) -> bool
118     where
119         Idx: PartialOrd<U>,
120         U: ?Sized + PartialOrd<Idx>,
121     {
122         <Self as RangeBounds<Idx>>::contains(self, item)
123     }
124
125     /// Returns `true` if the range contains no items.
126     ///
127     /// # Examples
128     ///
129     /// ```
130     /// #![feature(range_is_empty)]
131     ///
132     /// assert!(!(3..5).is_empty());
133     /// assert!( (3..3).is_empty());
134     /// assert!( (3..2).is_empty());
135     /// ```
136     ///
137     /// The range is empty if either side is incomparable:
138     ///
139     /// ```
140     /// #![feature(range_is_empty)]
141     ///
142     /// use std::f32::NAN;
143     /// assert!(!(3.0..5.0).is_empty());
144     /// assert!( (3.0..NAN).is_empty());
145     /// assert!( (NAN..5.0).is_empty());
146     /// ```
147     #[unstable(feature = "range_is_empty", reason = "recently added", issue = "48111")]
148     pub fn is_empty(&self) -> bool {
149         !(self.start < self.end)
150     }
151 }
152
153 /// A range only bounded inclusively below (`start..`).
154 ///
155 /// The `RangeFrom` `start..` contains all values with `x >= start`.
156 ///
157 /// *Note*: Currently, no overflow checking is done for the [`Iterator`]
158 /// implementation; if you use an integer range and the integer overflows, it
159 /// might panic in debug mode or create an endless loop in release mode. **This
160 /// overflow behavior might change in the future.**
161 ///
162 /// # Examples
163 ///
164 /// ```
165 /// assert_eq!((2..), std::ops::RangeFrom { start: 2 });
166 /// assert_eq!(2 + 3 + 4, (2..).take(3).sum());
167 ///
168 /// let arr = [0, 1, 2, 3, 4];
169 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
170 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
171 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
172 /// assert_eq!(arr[1..  ], [  1,2,3,4]);  // RangeFrom
173 /// assert_eq!(arr[1.. 3], [  1,2    ]);
174 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
175 /// ```
176 ///
177 /// [`Iterator`]: ../iter/trait.IntoIterator.html
178 #[doc(alias = "..")]
179 #[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
180 #[stable(feature = "rust1", since = "1.0.0")]
181 pub struct RangeFrom<Idx> {
182     /// The lower bound of the range (inclusive).
183     #[stable(feature = "rust1", since = "1.0.0")]
184     pub start: Idx,
185 }
186
187 #[stable(feature = "rust1", since = "1.0.0")]
188 impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
189     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
190         self.start.fmt(fmt)?;
191         write!(fmt, "..")?;
192         Ok(())
193     }
194 }
195
196 impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
197     /// Returns `true` if `item` is contained in the range.
198     ///
199     /// # Examples
200     ///
201     /// ```
202     /// use std::f32;
203     ///
204     /// assert!(!(3..).contains(&2));
205     /// assert!( (3..).contains(&3));
206     /// assert!( (3..).contains(&1_000_000_000));
207     ///
208     /// assert!( (0.0..).contains(&0.5));
209     /// assert!(!(0.0..).contains(&f32::NAN));
210     /// assert!(!(f32::NAN..).contains(&0.5));
211     /// ```
212     #[stable(feature = "range_contains", since = "1.35.0")]
213     pub fn contains<U>(&self, item: &U) -> bool
214     where
215         Idx: PartialOrd<U>,
216         U: ?Sized + PartialOrd<Idx>,
217     {
218         <Self as RangeBounds<Idx>>::contains(self, item)
219     }
220 }
221
222 /// A range only bounded exclusively above (`..end`).
223 ///
224 /// The `RangeTo` `..end` contains all values with `x < end`.
225 /// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
226 ///
227 /// # Examples
228 ///
229 /// The `..end` syntax is a `RangeTo`:
230 ///
231 /// ```
232 /// assert_eq!((..5), std::ops::RangeTo { end: 5 });
233 /// ```
234 ///
235 /// It does not have an [`IntoIterator`] implementation, so you can't use it in
236 /// a `for` loop directly. This won't compile:
237 ///
238 /// ```compile_fail,E0277
239 /// // error[E0277]: the trait bound `std::ops::RangeTo<{integer}>:
240 /// // std::iter::Iterator` is not satisfied
241 /// for i in ..5 {
242 ///     // ...
243 /// }
244 /// ```
245 ///
246 /// When used as a [slicing index], `RangeTo` produces a slice of all array
247 /// elements before the index indicated by `end`.
248 ///
249 /// ```
250 /// let arr = [0, 1, 2, 3, 4];
251 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
252 /// assert_eq!(arr[ .. 3], [0,1,2    ]);  // RangeTo
253 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
254 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
255 /// assert_eq!(arr[1.. 3], [  1,2    ]);
256 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
257 /// ```
258 ///
259 /// [`IntoIterator`]: ../iter/trait.Iterator.html
260 /// [`Iterator`]: ../iter/trait.IntoIterator.html
261 /// [slicing index]: ../slice/trait.SliceIndex.html
262 #[doc(alias = "..")]
263 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub struct RangeTo<Idx> {
266     /// The upper bound of the range (exclusive).
267     #[stable(feature = "rust1", since = "1.0.0")]
268     pub end: Idx,
269 }
270
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
273     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
274         write!(fmt, "..")?;
275         self.end.fmt(fmt)?;
276         Ok(())
277     }
278 }
279
280 impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
281     /// Returns `true` if `item` is contained in the range.
282     ///
283     /// # Examples
284     ///
285     /// ```
286     /// use std::f32;
287     ///
288     /// assert!( (..5).contains(&-1_000_000_000));
289     /// assert!( (..5).contains(&4));
290     /// assert!(!(..5).contains(&5));
291     ///
292     /// assert!( (..1.0).contains(&0.5));
293     /// assert!(!(..1.0).contains(&f32::NAN));
294     /// assert!(!(..f32::NAN).contains(&0.5));
295     /// ```
296     #[stable(feature = "range_contains", since = "1.35.0")]
297     pub fn contains<U>(&self, item: &U) -> bool
298     where
299         Idx: PartialOrd<U>,
300         U: ?Sized + PartialOrd<Idx>,
301     {
302         <Self as RangeBounds<Idx>>::contains(self, item)
303     }
304 }
305
306 /// A range bounded inclusively below and above (`start..=end`).
307 ///
308 /// The `RangeInclusive` `start..=end` contains all values with `x >= start`
309 /// and `x <= end`. It is empty unless `start <= end`.
310 ///
311 /// This iterator is [fused], but the specific values of `start` and `end` after
312 /// iteration has finished are **unspecified** other than that [`.is_empty()`]
313 /// will return `true` once no more values will be produced.
314 ///
315 /// [fused]: ../iter/trait.FusedIterator.html
316 /// [`.is_empty()`]: #method.is_empty
317 ///
318 /// # Examples
319 ///
320 /// ```
321 /// assert_eq!((3..=5), std::ops::RangeInclusive::new(3, 5));
322 /// assert_eq!(3 + 4 + 5, (3..=5).sum());
323 ///
324 /// let arr = [0, 1, 2, 3, 4];
325 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
326 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
327 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);
328 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
329 /// assert_eq!(arr[1.. 3], [  1,2    ]);
330 /// assert_eq!(arr[1..=3], [  1,2,3  ]);  // RangeInclusive
331 /// ```
332 #[doc(alias = "..=")]
333 #[derive(Clone)] // not Copy -- see #27186
334 #[stable(feature = "inclusive_range", since = "1.26.0")]
335 pub struct RangeInclusive<Idx> {
336     pub(crate) start: Idx,
337     pub(crate) end: Idx,
338     pub(crate) is_empty: Option<bool>,
339     // This field is:
340     //  - `None` when next() or next_back() was never called
341     //  - `Some(false)` when `start <= end` assuming no overflow
342     //  - `Some(true)` otherwise
343     // The field cannot be a simple `bool` because the `..=` constructor can
344     // accept non-PartialOrd types, also we want the constructor to be const.
345 }
346
347 trait RangeInclusiveEquality: Sized {
348     fn canonicalized_is_empty(range: &RangeInclusive<Self>) -> bool;
349 }
350
351 impl<T> RangeInclusiveEquality for T {
352     #[inline]
353     default fn canonicalized_is_empty(range: &RangeInclusive<Self>) -> bool {
354         range.is_empty.unwrap_or_default()
355     }
356 }
357
358 impl<T: PartialOrd> RangeInclusiveEquality for T {
359     #[inline]
360     fn canonicalized_is_empty(range: &RangeInclusive<Self>) -> bool {
361         range.is_empty()
362     }
363 }
364
365 #[stable(feature = "inclusive_range", since = "1.26.0")]
366 impl<Idx: PartialEq> PartialEq for RangeInclusive<Idx> {
367     #[inline]
368     fn eq(&self, other: &Self) -> bool {
369         self.start == other.start
370             && self.end == other.end
371             && RangeInclusiveEquality::canonicalized_is_empty(self)
372                 == RangeInclusiveEquality::canonicalized_is_empty(other)
373     }
374 }
375
376 #[stable(feature = "inclusive_range", since = "1.26.0")]
377 impl<Idx: Eq> Eq for RangeInclusive<Idx> {}
378
379 #[stable(feature = "inclusive_range", since = "1.26.0")]
380 impl<Idx: Hash> Hash for RangeInclusive<Idx> {
381     fn hash<H: Hasher>(&self, state: &mut H) {
382         self.start.hash(state);
383         self.end.hash(state);
384         RangeInclusiveEquality::canonicalized_is_empty(self).hash(state);
385     }
386 }
387
388 impl<Idx> RangeInclusive<Idx> {
389     /// Creates a new inclusive range. Equivalent to writing `start..=end`.
390     ///
391     /// # Examples
392     ///
393     /// ```
394     /// use std::ops::RangeInclusive;
395     ///
396     /// assert_eq!(3..=5, RangeInclusive::new(3, 5));
397     /// ```
398     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
399     #[inline]
400     #[rustc_promotable]
401     pub const fn new(start: Idx, end: Idx) -> Self {
402         Self {
403             start,
404             end,
405             is_empty: None,
406         }
407     }
408
409     /// Returns the lower bound of the range (inclusive).
410     ///
411     /// When using an inclusive range for iteration, the values of `start()` and
412     /// [`end()`] are unspecified after the iteration ended. To determine
413     /// whether the inclusive range is empty, use the [`is_empty()`] method
414     /// instead of comparing `start() > end()`.
415     ///
416     /// Note: the value returned by this method is unspecified after the range
417     /// has been iterated to exhaustion.
418     ///
419     /// [`end()`]: #method.end
420     /// [`is_empty()`]: #method.is_empty
421     ///
422     /// # Examples
423     ///
424     /// ```
425     /// assert_eq!((3..=5).start(), &3);
426     /// ```
427     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
428     #[inline]
429     pub const fn start(&self) -> &Idx {
430         &self.start
431     }
432
433     /// Returns the upper bound of the range (inclusive).
434     ///
435     /// When using an inclusive range for iteration, the values of [`start()`]
436     /// and `end()` are unspecified after the iteration ended. To determine
437     /// whether the inclusive range is empty, use the [`is_empty()`] method
438     /// instead of comparing `start() > end()`.
439     ///
440     /// Note: the value returned by this method is unspecified after the range
441     /// has been iterated to exhaustion.
442     ///
443     /// [`start()`]: #method.start
444     /// [`is_empty()`]: #method.is_empty
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// assert_eq!((3..=5).end(), &5);
450     /// ```
451     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
452     #[inline]
453     pub const fn end(&self) -> &Idx {
454         &self.end
455     }
456
457     /// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
458     ///
459     /// Note: the value returned by this method is unspecified after the range
460     /// has been iterated to exhaustion.
461     ///
462     /// # Examples
463     ///
464     /// ```
465     /// assert_eq!((3..=5).into_inner(), (3, 5));
466     /// ```
467     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
468     #[inline]
469     pub fn into_inner(self) -> (Idx, Idx) {
470         (self.start, self.end)
471     }
472 }
473
474 #[stable(feature = "inclusive_range", since = "1.26.0")]
475 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
476     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
477         self.start.fmt(fmt)?;
478         write!(fmt, "..=")?;
479         self.end.fmt(fmt)?;
480         Ok(())
481     }
482 }
483
484 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
485     /// Returns `true` if `item` is contained in the range.
486     ///
487     /// # Examples
488     ///
489     /// ```
490     /// use std::f32;
491     ///
492     /// assert!(!(3..=5).contains(&2));
493     /// assert!( (3..=5).contains(&3));
494     /// assert!( (3..=5).contains(&4));
495     /// assert!( (3..=5).contains(&5));
496     /// assert!(!(3..=5).contains(&6));
497     ///
498     /// assert!( (3..=3).contains(&3));
499     /// assert!(!(3..=2).contains(&3));
500     ///
501     /// assert!( (0.0..=1.0).contains(&1.0));
502     /// assert!(!(0.0..=1.0).contains(&f32::NAN));
503     /// assert!(!(0.0..=f32::NAN).contains(&0.0));
504     /// assert!(!(f32::NAN..=1.0).contains(&1.0));
505     /// ```
506     #[stable(feature = "range_contains", since = "1.35.0")]
507     pub fn contains<U>(&self, item: &U) -> bool
508     where
509         Idx: PartialOrd<U>,
510         U: ?Sized + PartialOrd<Idx>,
511     {
512         <Self as RangeBounds<Idx>>::contains(self, item)
513     }
514
515     /// Returns `true` if the range contains no items.
516     ///
517     /// # Examples
518     ///
519     /// ```
520     /// #![feature(range_is_empty)]
521     ///
522     /// assert!(!(3..=5).is_empty());
523     /// assert!(!(3..=3).is_empty());
524     /// assert!( (3..=2).is_empty());
525     /// ```
526     ///
527     /// The range is empty if either side is incomparable:
528     ///
529     /// ```
530     /// #![feature(range_is_empty)]
531     ///
532     /// use std::f32::NAN;
533     /// assert!(!(3.0..=5.0).is_empty());
534     /// assert!( (3.0..=NAN).is_empty());
535     /// assert!( (NAN..=5.0).is_empty());
536     /// ```
537     ///
538     /// This method returns `true` after iteration has finished:
539     ///
540     /// ```
541     /// #![feature(range_is_empty)]
542     ///
543     /// let mut r = 3..=5;
544     /// for _ in r.by_ref() {}
545     /// // Precise field values are unspecified here
546     /// assert!(r.is_empty());
547     /// ```
548     #[unstable(feature = "range_is_empty", reason = "recently added", issue = "48111")]
549     #[inline]
550     pub fn is_empty(&self) -> bool {
551         self.is_empty.unwrap_or_else(|| !(self.start <= self.end))
552     }
553
554     // If this range's `is_empty` is field is unknown (`None`), update it to be a concrete value.
555     #[inline]
556     pub(crate) fn compute_is_empty(&mut self) {
557         if self.is_empty.is_none() {
558             self.is_empty = Some(!(self.start <= self.end));
559         }
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  ]);  // 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 /// [`IntoIterator`]: ../iter/trait.Iterator.html
601 /// [`Iterator`]: ../iter/trait.IntoIterator.html
602 /// [slicing index]: ../slice/trait.SliceIndex.html
603 #[doc(alias = "..=")]
604 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
605 #[stable(feature = "inclusive_range", since = "1.26.0")]
606 pub struct RangeToInclusive<Idx> {
607     /// The upper bound of the range (inclusive)
608     #[stable(feature = "inclusive_range", since = "1.26.0")]
609     pub end: Idx,
610 }
611
612 #[stable(feature = "inclusive_range", since = "1.26.0")]
613 impl<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 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
622     /// Returns `true` if `item` is contained in the range.
623     ///
624     /// # Examples
625     ///
626     /// ```
627     /// use std::f32;
628     ///
629     /// assert!( (..=5).contains(&-1_000_000_000));
630     /// assert!( (..=5).contains(&5));
631     /// assert!(!(..=5).contains(&6));
632     ///
633     /// assert!( (..=1.0).contains(&1.0));
634     /// assert!(!(..=1.0).contains(&f32::NAN));
635     /// assert!(!(..=f32::NAN).contains(&0.5));
636     /// ```
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 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
687 pub 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
699 #[stable(feature = "collections_range", since = "1.28.0")]
700 /// `RangeBounds` is implemented by Rust's built-in range types, produced
701 /// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
702 pub trait RangeBounds<T: ?Sized> {
703     /// Start index bound.
704     ///
705     /// Returns the start value as a `Bound`.
706     ///
707     /// # Examples
708     ///
709     /// ```
710     /// # fn main() {
711     /// use std::ops::Bound::*;
712     /// use std::ops::RangeBounds;
713     ///
714     /// assert_eq!((..10).start_bound(), Unbounded);
715     /// assert_eq!((3..10).start_bound(), Included(&3));
716     /// # }
717     /// ```
718     #[stable(feature = "collections_range", since = "1.28.0")]
719     fn start_bound(&self) -> Bound<&T>;
720
721     /// End index bound.
722     ///
723     /// Returns the end value as a `Bound`.
724     ///
725     /// # Examples
726     ///
727     /// ```
728     /// # fn main() {
729     /// use std::ops::Bound::*;
730     /// use std::ops::RangeBounds;
731     ///
732     /// assert_eq!((3..).end_bound(), Unbounded);
733     /// assert_eq!((3..10).end_bound(), Excluded(&10));
734     /// # }
735     /// ```
736     #[stable(feature = "collections_range", since = "1.28.0")]
737     fn end_bound(&self) -> Bound<&T>;
738
739     /// Returns `true` if `item` is contained in the range.
740     ///
741     /// # Examples
742     ///
743     /// ```
744     /// use std::f32;
745     ///
746     /// assert!( (3..5).contains(&4));
747     /// assert!(!(3..5).contains(&2));
748     ///
749     /// assert!( (0.0..1.0).contains(&0.5));
750     /// assert!(!(0.0..1.0).contains(&f32::NAN));
751     /// assert!(!(0.0..f32::NAN).contains(&0.5));
752     /// assert!(!(f32::NAN..1.0).contains(&0.5));
753     #[stable(feature = "range_contains", since = "1.35.0")]
754     fn contains<U>(&self, item: &U) -> bool
755     where
756         T: PartialOrd<U>,
757         U: ?Sized + PartialOrd<T>,
758     {
759         (match self.start_bound() {
760             Included(ref start) => *start <= item,
761             Excluded(ref start) => *start < item,
762             Unbounded => true,
763         }) && (match self.end_bound() {
764             Included(ref end) => item <= *end,
765             Excluded(ref end) => item < *end,
766             Unbounded => true,
767         })
768     }
769 }
770
771 use self::Bound::{Excluded, Included, Unbounded};
772
773 #[stable(feature = "collections_range", since = "1.28.0")]
774 impl<T: ?Sized> RangeBounds<T> for RangeFull {
775     fn start_bound(&self) -> Bound<&T> {
776         Unbounded
777     }
778     fn end_bound(&self) -> Bound<&T> {
779         Unbounded
780     }
781 }
782
783 #[stable(feature = "collections_range", since = "1.28.0")]
784 impl<T> RangeBounds<T> for RangeFrom<T> {
785     fn start_bound(&self) -> Bound<&T> {
786         Included(&self.start)
787     }
788     fn end_bound(&self) -> Bound<&T> {
789         Unbounded
790     }
791 }
792
793 #[stable(feature = "collections_range", since = "1.28.0")]
794 impl<T> RangeBounds<T> for RangeTo<T> {
795     fn start_bound(&self) -> Bound<&T> {
796         Unbounded
797     }
798     fn end_bound(&self) -> Bound<&T> {
799         Excluded(&self.end)
800     }
801 }
802
803 #[stable(feature = "collections_range", since = "1.28.0")]
804 impl<T> RangeBounds<T> for Range<T> {
805     fn start_bound(&self) -> Bound<&T> {
806         Included(&self.start)
807     }
808     fn end_bound(&self) -> Bound<&T> {
809         Excluded(&self.end)
810     }
811 }
812
813 #[stable(feature = "collections_range", since = "1.28.0")]
814 impl<T> RangeBounds<T> for RangeInclusive<T> {
815     fn start_bound(&self) -> Bound<&T> {
816         Included(&self.start)
817     }
818     fn end_bound(&self) -> Bound<&T> {
819         Included(&self.end)
820     }
821 }
822
823 #[stable(feature = "collections_range", since = "1.28.0")]
824 impl<T> RangeBounds<T> for RangeToInclusive<T> {
825     fn start_bound(&self) -> Bound<&T> {
826         Unbounded
827     }
828     fn end_bound(&self) -> Bound<&T> {
829         Included(&self.end)
830     }
831 }
832
833 #[stable(feature = "collections_range", since = "1.28.0")]
834 impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
835     fn start_bound(&self) -> Bound<&T> {
836         match *self {
837             (Included(ref start), _) => Included(start),
838             (Excluded(ref start), _) => Excluded(start),
839             (Unbounded, _) => Unbounded,
840         }
841     }
842
843     fn end_bound(&self) -> Bound<&T> {
844         match *self {
845             (_, Included(ref end)) => Included(end),
846             (_, Excluded(ref end)) => Excluded(end),
847             (_, Unbounded) => Unbounded,
848         }
849     }
850 }
851
852 #[stable(feature = "collections_range", since = "1.28.0")]
853 impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
854     fn start_bound(&self) -> Bound<&T> {
855         self.0
856     }
857
858     fn end_bound(&self) -> Bound<&T> {
859         self.1
860     }
861 }
862
863 #[stable(feature = "collections_range", since = "1.28.0")]
864 impl<T> RangeBounds<T> for RangeFrom<&T> {
865     fn start_bound(&self) -> Bound<&T> {
866         Included(self.start)
867     }
868     fn end_bound(&self) -> Bound<&T> {
869         Unbounded
870     }
871 }
872
873 #[stable(feature = "collections_range", since = "1.28.0")]
874 impl<T> RangeBounds<T> for RangeTo<&T> {
875     fn start_bound(&self) -> Bound<&T> {
876         Unbounded
877     }
878     fn end_bound(&self) -> Bound<&T> {
879         Excluded(self.end)
880     }
881 }
882
883 #[stable(feature = "collections_range", since = "1.28.0")]
884 impl<T> RangeBounds<T> for Range<&T> {
885     fn start_bound(&self) -> Bound<&T> {
886         Included(self.start)
887     }
888     fn end_bound(&self) -> Bound<&T> {
889         Excluded(self.end)
890     }
891 }
892
893 #[stable(feature = "collections_range", since = "1.28.0")]
894 impl<T> RangeBounds<T> for RangeInclusive<&T> {
895     fn start_bound(&self) -> Bound<&T> {
896         Included(self.start)
897     }
898     fn end_bound(&self) -> Bound<&T> {
899         Included(self.end)
900     }
901 }
902
903 #[stable(feature = "collections_range", since = "1.28.0")]
904 impl<T> RangeBounds<T> for RangeToInclusive<&T> {
905     fn start_bound(&self) -> Bound<&T> {
906         Unbounded
907     }
908     fn end_bound(&self) -> Bound<&T> {
909         Included(self.end)
910     }
911 }