]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/range.rs
Rollup merge of #69007 - GuillaumeGomez:clean-up-e0283, r=Dylan-DPC
[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     // Note that the fields here are not public to allow changing the
337     // representation in the future; in particular, while we could plausibly
338     // expose start/end, modifying them without changing (future/current)
339     // private fields may lead to incorrect behavior, so we don't want to
340     // support that mode.
341     pub(crate) start: Idx,
342     pub(crate) end: Idx,
343     pub(crate) is_empty: Option<bool>,
344     // This field is:
345     //  - `None` when next() or next_back() was never called
346     //  - `Some(false)` when `start < end`
347     //  - `Some(true)` when `end < start`
348     //  - `Some(false)` when `start == end` and the range hasn't yet completed iteration
349     //  - `Some(true)` when `start == end` and the range has completed iteration
350     // The field cannot be a simple `bool` because the `..=` constructor can
351     // accept non-PartialOrd types, also we want the constructor to be const.
352 }
353
354 #[stable(feature = "inclusive_range", since = "1.26.0")]
355 impl<Idx: PartialEq> PartialEq for RangeInclusive<Idx> {
356     #[inline]
357     fn eq(&self, other: &Self) -> bool {
358         self.start == other.start
359             && self.end == other.end
360             && self.is_exhausted() == other.is_exhausted()
361     }
362 }
363
364 #[stable(feature = "inclusive_range", since = "1.26.0")]
365 impl<Idx: Eq> Eq for RangeInclusive<Idx> {}
366
367 #[stable(feature = "inclusive_range", since = "1.26.0")]
368 impl<Idx: Hash> Hash for RangeInclusive<Idx> {
369     fn hash<H: Hasher>(&self, state: &mut H) {
370         self.start.hash(state);
371         self.end.hash(state);
372         // Ideally we would hash `is_exhausted` here as well, but there's no
373         // way for us to call it.
374     }
375 }
376
377 impl<Idx> RangeInclusive<Idx> {
378     /// Creates a new inclusive range. Equivalent to writing `start..=end`.
379     ///
380     /// # Examples
381     ///
382     /// ```
383     /// use std::ops::RangeInclusive;
384     ///
385     /// assert_eq!(3..=5, RangeInclusive::new(3, 5));
386     /// ```
387     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
388     #[inline]
389     #[rustc_promotable]
390     #[rustc_const_stable(feature = "const_range_new", since = "1.32.0")]
391     pub const fn new(start: Idx, end: Idx) -> Self {
392         Self { start, end, is_empty: None }
393     }
394
395     /// Returns the lower bound of the range (inclusive).
396     ///
397     /// When using an inclusive range for iteration, the values of `start()` and
398     /// [`end()`] are unspecified after the iteration ended. To determine
399     /// whether the inclusive range is empty, use the [`is_empty()`] method
400     /// instead of comparing `start() > end()`.
401     ///
402     /// Note: the value returned by this method is unspecified after the range
403     /// has been iterated to exhaustion.
404     ///
405     /// [`end()`]: #method.end
406     /// [`is_empty()`]: #method.is_empty
407     ///
408     /// # Examples
409     ///
410     /// ```
411     /// assert_eq!((3..=5).start(), &3);
412     /// ```
413     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
414     #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
415     #[inline]
416     pub const fn start(&self) -> &Idx {
417         &self.start
418     }
419
420     /// Returns the upper bound of the range (inclusive).
421     ///
422     /// When using an inclusive range for iteration, the values of [`start()`]
423     /// and `end()` are unspecified after the iteration ended. To determine
424     /// whether the inclusive range is empty, use the [`is_empty()`] method
425     /// instead of comparing `start() > end()`.
426     ///
427     /// Note: the value returned by this method is unspecified after the range
428     /// has been iterated to exhaustion.
429     ///
430     /// [`start()`]: #method.start
431     /// [`is_empty()`]: #method.is_empty
432     ///
433     /// # Examples
434     ///
435     /// ```
436     /// assert_eq!((3..=5).end(), &5);
437     /// ```
438     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
439     #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
440     #[inline]
441     pub const fn end(&self) -> &Idx {
442         &self.end
443     }
444
445     /// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
446     ///
447     /// Note: the value returned by this method is unspecified after the range
448     /// has been iterated to exhaustion.
449     ///
450     /// # Examples
451     ///
452     /// ```
453     /// assert_eq!((3..=5).into_inner(), (3, 5));
454     /// ```
455     #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
456     #[inline]
457     pub fn into_inner(self) -> (Idx, Idx) {
458         (self.start, self.end)
459     }
460 }
461
462 #[stable(feature = "inclusive_range", since = "1.26.0")]
463 impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
464     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
465         self.start.fmt(fmt)?;
466         write!(fmt, "..=")?;
467         self.end.fmt(fmt)?;
468         Ok(())
469     }
470 }
471
472 impl<Idx: PartialEq<Idx>> RangeInclusive<Idx> {
473     // Returns true if this is a range that started non-empty, and was iterated
474     // to exhaustion.
475     fn is_exhausted(&self) -> bool {
476         Some(true) == self.is_empty && self.start == self.end
477     }
478 }
479
480 impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
481     /// Returns `true` if `item` is contained in the range.
482     ///
483     /// # Examples
484     ///
485     /// ```
486     /// use std::f32;
487     ///
488     /// assert!(!(3..=5).contains(&2));
489     /// assert!( (3..=5).contains(&3));
490     /// assert!( (3..=5).contains(&4));
491     /// assert!( (3..=5).contains(&5));
492     /// assert!(!(3..=5).contains(&6));
493     ///
494     /// assert!( (3..=3).contains(&3));
495     /// assert!(!(3..=2).contains(&3));
496     ///
497     /// assert!( (0.0..=1.0).contains(&1.0));
498     /// assert!(!(0.0..=1.0).contains(&f32::NAN));
499     /// assert!(!(0.0..=f32::NAN).contains(&0.0));
500     /// assert!(!(f32::NAN..=1.0).contains(&1.0));
501     /// ```
502     #[stable(feature = "range_contains", since = "1.35.0")]
503     pub fn contains<U>(&self, item: &U) -> bool
504     where
505         Idx: PartialOrd<U>,
506         U: ?Sized + PartialOrd<Idx>,
507     {
508         <Self as RangeBounds<Idx>>::contains(self, item)
509     }
510
511     /// Returns `true` if the range contains no items.
512     ///
513     /// # Examples
514     ///
515     /// ```
516     /// #![feature(range_is_empty)]
517     ///
518     /// assert!(!(3..=5).is_empty());
519     /// assert!(!(3..=3).is_empty());
520     /// assert!( (3..=2).is_empty());
521     /// ```
522     ///
523     /// The range is empty if either side is incomparable:
524     ///
525     /// ```
526     /// #![feature(range_is_empty)]
527     ///
528     /// use std::f32::NAN;
529     /// assert!(!(3.0..=5.0).is_empty());
530     /// assert!( (3.0..=NAN).is_empty());
531     /// assert!( (NAN..=5.0).is_empty());
532     /// ```
533     ///
534     /// This method returns `true` after iteration has finished:
535     ///
536     /// ```
537     /// #![feature(range_is_empty)]
538     ///
539     /// let mut r = 3..=5;
540     /// for _ in r.by_ref() {}
541     /// // Precise field values are unspecified here
542     /// assert!(r.is_empty());
543     /// ```
544     #[unstable(feature = "range_is_empty", reason = "recently added", issue = "48111")]
545     #[inline]
546     pub fn is_empty(&self) -> bool {
547         self.is_empty.unwrap_or_else(|| !(self.start <= self.end))
548     }
549
550     // If this range's `is_empty` is field is unknown (`None`), update it to be a concrete value.
551     #[inline]
552     pub(crate) fn compute_is_empty(&mut self) {
553         if self.is_empty.is_none() {
554             self.is_empty = Some(!(self.start <= self.end));
555         }
556     }
557 }
558
559 /// A range only bounded inclusively above (`..=end`).
560 ///
561 /// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
562 /// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
563 ///
564 /// # Examples
565 ///
566 /// The `..=end` syntax is a `RangeToInclusive`:
567 ///
568 /// ```
569 /// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
570 /// ```
571 ///
572 /// It does not have an [`IntoIterator`] implementation, so you can't use it in a
573 /// `for` loop directly. This won't compile:
574 ///
575 /// ```compile_fail,E0277
576 /// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
577 /// // std::iter::Iterator` is not satisfied
578 /// for i in ..=5 {
579 ///     // ...
580 /// }
581 /// ```
582 ///
583 /// When used as a [slicing index], `RangeToInclusive` produces a slice of all
584 /// array elements up to and including the index indicated by `end`.
585 ///
586 /// ```
587 /// let arr = [0, 1, 2, 3, 4];
588 /// assert_eq!(arr[ ..  ], [0,1,2,3,4]);
589 /// assert_eq!(arr[ .. 3], [0,1,2    ]);
590 /// assert_eq!(arr[ ..=3], [0,1,2,3  ]);  // RangeToInclusive
591 /// assert_eq!(arr[1..  ], [  1,2,3,4]);
592 /// assert_eq!(arr[1.. 3], [  1,2    ]);
593 /// assert_eq!(arr[1..=3], [  1,2,3  ]);
594 /// ```
595 ///
596 /// [`IntoIterator`]: ../iter/trait.Iterator.html
597 /// [`Iterator`]: ../iter/trait.IntoIterator.html
598 /// [slicing index]: ../slice/trait.SliceIndex.html
599 #[doc(alias = "..=")]
600 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
601 #[stable(feature = "inclusive_range", since = "1.26.0")]
602 pub struct RangeToInclusive<Idx> {
603     /// The upper bound of the range (inclusive)
604     #[stable(feature = "inclusive_range", since = "1.26.0")]
605     pub end: Idx,
606 }
607
608 #[stable(feature = "inclusive_range", since = "1.26.0")]
609 impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
610     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
611         write!(fmt, "..=")?;
612         self.end.fmt(fmt)?;
613         Ok(())
614     }
615 }
616
617 impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
618     /// Returns `true` if `item` is contained in the range.
619     ///
620     /// # Examples
621     ///
622     /// ```
623     /// use std::f32;
624     ///
625     /// assert!( (..=5).contains(&-1_000_000_000));
626     /// assert!( (..=5).contains(&5));
627     /// assert!(!(..=5).contains(&6));
628     ///
629     /// assert!( (..=1.0).contains(&1.0));
630     /// assert!(!(..=1.0).contains(&f32::NAN));
631     /// assert!(!(..=f32::NAN).contains(&0.5));
632     /// ```
633     #[stable(feature = "range_contains", since = "1.35.0")]
634     pub fn contains<U>(&self, item: &U) -> bool
635     where
636         Idx: PartialOrd<U>,
637         U: ?Sized + PartialOrd<Idx>,
638     {
639         <Self as RangeBounds<Idx>>::contains(self, item)
640     }
641 }
642
643 // RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
644 // because underflow would be possible with (..0).into()
645
646 /// An endpoint of a range of keys.
647 ///
648 /// # Examples
649 ///
650 /// `Bound`s are range endpoints:
651 ///
652 /// ```
653 /// use std::ops::Bound::*;
654 /// use std::ops::RangeBounds;
655 ///
656 /// assert_eq!((..100).start_bound(), Unbounded);
657 /// assert_eq!((1..12).start_bound(), Included(&1));
658 /// assert_eq!((1..12).end_bound(), Excluded(&12));
659 /// ```
660 ///
661 /// Using a tuple of `Bound`s as an argument to [`BTreeMap::range`].
662 /// Note that in most cases, it's better to use range syntax (`1..5`) instead.
663 ///
664 /// ```
665 /// use std::collections::BTreeMap;
666 /// use std::ops::Bound::{Excluded, Included, Unbounded};
667 ///
668 /// let mut map = BTreeMap::new();
669 /// map.insert(3, "a");
670 /// map.insert(5, "b");
671 /// map.insert(8, "c");
672 ///
673 /// for (key, value) in map.range((Excluded(3), Included(8))) {
674 ///     println!("{}: {}", key, value);
675 /// }
676 ///
677 /// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());
678 /// ```
679 ///
680 /// [`BTreeMap::range`]: ../../std/collections/btree_map/struct.BTreeMap.html#method.range
681 #[stable(feature = "collections_bound", since = "1.17.0")]
682 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
683 pub enum Bound<T> {
684     /// An inclusive bound.
685     #[stable(feature = "collections_bound", since = "1.17.0")]
686     Included(#[stable(feature = "collections_bound", since = "1.17.0")] T),
687     /// An exclusive bound.
688     #[stable(feature = "collections_bound", since = "1.17.0")]
689     Excluded(#[stable(feature = "collections_bound", since = "1.17.0")] T),
690     /// An infinite endpoint. Indicates that there is no bound in this direction.
691     #[stable(feature = "collections_bound", since = "1.17.0")]
692     Unbounded,
693 }
694
695 impl<T: Clone> Bound<&T> {
696     /// Map a `Bound<&T>` to a `Bound<T>` by cloning the contents of the bound.
697     ///
698     /// # Examples
699     ///
700     /// ```
701     /// #![feature(bound_cloned)]
702     /// use std::ops::Bound::*;
703     /// use std::ops::RangeBounds;
704     ///
705     /// assert_eq!((1..12).start_bound(), Included(&1));
706     /// assert_eq!((1..12).start_bound().cloned(), Included(1));
707     /// ```
708     #[unstable(feature = "bound_cloned", issue = "61356")]
709     pub fn cloned(self) -> Bound<T> {
710         match self {
711             Bound::Unbounded => Bound::Unbounded,
712             Bound::Included(x) => Bound::Included(x.clone()),
713             Bound::Excluded(x) => Bound::Excluded(x.clone()),
714         }
715     }
716 }
717
718 #[stable(feature = "collections_range", since = "1.28.0")]
719 /// `RangeBounds` is implemented by Rust's built-in range types, produced
720 /// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
721 pub trait RangeBounds<T: ?Sized> {
722     /// Start index bound.
723     ///
724     /// Returns the start value as a `Bound`.
725     ///
726     /// # Examples
727     ///
728     /// ```
729     /// # fn main() {
730     /// use std::ops::Bound::*;
731     /// use std::ops::RangeBounds;
732     ///
733     /// assert_eq!((..10).start_bound(), Unbounded);
734     /// assert_eq!((3..10).start_bound(), Included(&3));
735     /// # }
736     /// ```
737     #[stable(feature = "collections_range", since = "1.28.0")]
738     fn start_bound(&self) -> Bound<&T>;
739
740     /// End index bound.
741     ///
742     /// Returns the end value as a `Bound`.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// # fn main() {
748     /// use std::ops::Bound::*;
749     /// use std::ops::RangeBounds;
750     ///
751     /// assert_eq!((3..).end_bound(), Unbounded);
752     /// assert_eq!((3..10).end_bound(), Excluded(&10));
753     /// # }
754     /// ```
755     #[stable(feature = "collections_range", since = "1.28.0")]
756     fn end_bound(&self) -> Bound<&T>;
757
758     /// Returns `true` if `item` is contained in the range.
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// use std::f32;
764     ///
765     /// assert!( (3..5).contains(&4));
766     /// assert!(!(3..5).contains(&2));
767     ///
768     /// assert!( (0.0..1.0).contains(&0.5));
769     /// assert!(!(0.0..1.0).contains(&f32::NAN));
770     /// assert!(!(0.0..f32::NAN).contains(&0.5));
771     /// assert!(!(f32::NAN..1.0).contains(&0.5));
772     #[stable(feature = "range_contains", since = "1.35.0")]
773     fn contains<U>(&self, item: &U) -> bool
774     where
775         T: PartialOrd<U>,
776         U: ?Sized + PartialOrd<T>,
777     {
778         (match self.start_bound() {
779             Included(ref start) => *start <= item,
780             Excluded(ref start) => *start < item,
781             Unbounded => true,
782         }) && (match self.end_bound() {
783             Included(ref end) => item <= *end,
784             Excluded(ref end) => item < *end,
785             Unbounded => true,
786         })
787     }
788 }
789
790 use self::Bound::{Excluded, Included, Unbounded};
791
792 #[stable(feature = "collections_range", since = "1.28.0")]
793 impl<T: ?Sized> RangeBounds<T> for RangeFull {
794     fn start_bound(&self) -> Bound<&T> {
795         Unbounded
796     }
797     fn end_bound(&self) -> Bound<&T> {
798         Unbounded
799     }
800 }
801
802 #[stable(feature = "collections_range", since = "1.28.0")]
803 impl<T> RangeBounds<T> for RangeFrom<T> {
804     fn start_bound(&self) -> Bound<&T> {
805         Included(&self.start)
806     }
807     fn end_bound(&self) -> Bound<&T> {
808         Unbounded
809     }
810 }
811
812 #[stable(feature = "collections_range", since = "1.28.0")]
813 impl<T> RangeBounds<T> for RangeTo<T> {
814     fn start_bound(&self) -> Bound<&T> {
815         Unbounded
816     }
817     fn end_bound(&self) -> Bound<&T> {
818         Excluded(&self.end)
819     }
820 }
821
822 #[stable(feature = "collections_range", since = "1.28.0")]
823 impl<T> RangeBounds<T> for Range<T> {
824     fn start_bound(&self) -> Bound<&T> {
825         Included(&self.start)
826     }
827     fn end_bound(&self) -> Bound<&T> {
828         Excluded(&self.end)
829     }
830 }
831
832 #[stable(feature = "collections_range", since = "1.28.0")]
833 impl<T> RangeBounds<T> for RangeInclusive<T> {
834     fn start_bound(&self) -> Bound<&T> {
835         Included(&self.start)
836     }
837     fn end_bound(&self) -> Bound<&T> {
838         Included(&self.end)
839     }
840 }
841
842 #[stable(feature = "collections_range", since = "1.28.0")]
843 impl<T> RangeBounds<T> for RangeToInclusive<T> {
844     fn start_bound(&self) -> Bound<&T> {
845         Unbounded
846     }
847     fn end_bound(&self) -> Bound<&T> {
848         Included(&self.end)
849     }
850 }
851
852 #[stable(feature = "collections_range", since = "1.28.0")]
853 impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
854     fn start_bound(&self) -> Bound<&T> {
855         match *self {
856             (Included(ref start), _) => Included(start),
857             (Excluded(ref start), _) => Excluded(start),
858             (Unbounded, _) => Unbounded,
859         }
860     }
861
862     fn end_bound(&self) -> Bound<&T> {
863         match *self {
864             (_, Included(ref end)) => Included(end),
865             (_, Excluded(ref end)) => Excluded(end),
866             (_, Unbounded) => Unbounded,
867         }
868     }
869 }
870
871 #[stable(feature = "collections_range", since = "1.28.0")]
872 impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
873     fn start_bound(&self) -> Bound<&T> {
874         self.0
875     }
876
877     fn end_bound(&self) -> Bound<&T> {
878         self.1
879     }
880 }
881
882 #[stable(feature = "collections_range", since = "1.28.0")]
883 impl<T> RangeBounds<T> for RangeFrom<&T> {
884     fn start_bound(&self) -> Bound<&T> {
885         Included(self.start)
886     }
887     fn end_bound(&self) -> Bound<&T> {
888         Unbounded
889     }
890 }
891
892 #[stable(feature = "collections_range", since = "1.28.0")]
893 impl<T> RangeBounds<T> for RangeTo<&T> {
894     fn start_bound(&self) -> Bound<&T> {
895         Unbounded
896     }
897     fn end_bound(&self) -> Bound<&T> {
898         Excluded(self.end)
899     }
900 }
901
902 #[stable(feature = "collections_range", since = "1.28.0")]
903 impl<T> RangeBounds<T> for Range<&T> {
904     fn start_bound(&self) -> Bound<&T> {
905         Included(self.start)
906     }
907     fn end_bound(&self) -> Bound<&T> {
908         Excluded(self.end)
909     }
910 }
911
912 #[stable(feature = "collections_range", since = "1.28.0")]
913 impl<T> RangeBounds<T> for RangeInclusive<&T> {
914     fn start_bound(&self) -> Bound<&T> {
915         Included(self.start)
916     }
917     fn end_bound(&self) -> Bound<&T> {
918         Included(self.end)
919     }
920 }
921
922 #[stable(feature = "collections_range", since = "1.28.0")]
923 impl<T> RangeBounds<T> for RangeToInclusive<&T> {
924     fn start_bound(&self) -> Bound<&T> {
925         Unbounded
926     }
927     fn end_bound(&self) -> Bound<&T> {
928         Included(self.end)
929     }
930 }