1
#[cfg(not(feature = "ferrocene_certified"))]
2
use crate::fmt;
3
#[cfg(not(feature = "ferrocene_certified"))]
4
use crate::hash::Hash;
5

            
6
/// An unbounded range (`..`).
7
///
8
/// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`.
9
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
10
///
11
/// # Examples
12
///
13
/// The `..` syntax is a `RangeFull`:
14
///
15
/// ```
16
/// assert_eq!(.., std::ops::RangeFull);
17
/// ```
18
///
19
/// It does not have an [`IntoIterator`] implementation, so you can't use it in
20
/// a `for` loop directly. This won't compile:
21
///
22
/// ```compile_fail,E0277
23
/// for i in .. {
24
///     // ...
25
/// }
26
/// ```
27
///
28
/// Used as a [slicing index], `RangeFull` produces the full array as a slice.
29
///
30
/// ```
31
/// let arr = [0, 1, 2, 3, 4];
32
/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]); // This is the `RangeFull`
33
/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
34
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
35
/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
36
/// assert_eq!(arr[1.. 3], [   1, 2      ]);
37
/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
38
/// ```
39
///
40
/// [slicing index]: crate::slice::SliceIndex
41
#[lang = "RangeFull"]
42
#[doc(alias = "..")]
43
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Clone, Default, PartialEq, Eq, Hash))]
44
#[stable(feature = "rust1", since = "1.0.0")]
45
pub struct RangeFull;
46

            
47
#[stable(feature = "rust1", since = "1.0.0")]
48
#[cfg(not(feature = "ferrocene_certified"))]
49
impl fmt::Debug for RangeFull {
50
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
51
        write!(fmt, "..")
52
    }
53
}
54

            
55
/// A (half-open) range bounded inclusively below and exclusively above
56
/// (`start..end`).
57
///
58
/// The range `start..end` contains all values with `start <= x < end`.
59
/// It is empty if `start >= end`.
60
///
61
/// # Examples
62
///
63
/// The `start..end` syntax is a `Range`:
64
///
65
/// ```
66
/// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
67
/// assert_eq!(3 + 4 + 5, (3..6).sum());
68
/// ```
69
///
70
/// ```
71
/// let arr = [0, 1, 2, 3, 4];
72
/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
73
/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
74
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
75
/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
76
/// assert_eq!(arr[1.. 3], [   1, 2      ]); // This is a `Range`
77
/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
78
/// ```
79
#[lang = "Range"]
80
#[doc(alias = "..")]
81
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Clone, Default, PartialEq, Eq, Hash))] // not Copy -- see #27186
82
#[stable(feature = "rust1", since = "1.0.0")]
83
pub struct Range<Idx> {
84
    /// The lower bound of the range (inclusive).
85
    #[stable(feature = "rust1", since = "1.0.0")]
86
    pub start: Idx,
87
    /// The upper bound of the range (exclusive).
88
    #[stable(feature = "rust1", since = "1.0.0")]
89
    pub end: Idx,
90
}
91

            
92
#[stable(feature = "rust1", since = "1.0.0")]
93
#[cfg(not(feature = "ferrocene_certified"))]
94
impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
95
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
96
        self.start.fmt(fmt)?;
97
        write!(fmt, "..")?;
98
        self.end.fmt(fmt)?;
99
        Ok(())
100
    }
101
}
102

            
103
#[cfg(not(feature = "ferrocene_certified"))]
104
impl<Idx: PartialOrd<Idx>> Range<Idx> {
105
    /// Returns `true` if `item` is contained in the range.
106
    ///
107
    /// # Examples
108
    ///
109
    /// ```
110
    /// assert!(!(3..5).contains(&2));
111
    /// assert!( (3..5).contains(&3));
112
    /// assert!( (3..5).contains(&4));
113
    /// assert!(!(3..5).contains(&5));
114
    ///
115
    /// assert!(!(3..3).contains(&3));
116
    /// assert!(!(3..2).contains(&3));
117
    ///
118
    /// assert!( (0.0..1.0).contains(&0.5));
119
    /// assert!(!(0.0..1.0).contains(&f32::NAN));
120
    /// assert!(!(0.0..f32::NAN).contains(&0.5));
121
    /// assert!(!(f32::NAN..1.0).contains(&0.5));
122
    /// ```
123
    #[inline]
124
    #[stable(feature = "range_contains", since = "1.35.0")]
125
    pub fn contains<U>(&self, item: &U) -> bool
126
    where
127
        Idx: PartialOrd<U>,
128
        U: ?Sized + PartialOrd<Idx>,
129
    {
130
        <Self as RangeBounds<Idx>>::contains(self, item)
131
    }
132

            
133
    /// Returns `true` if the range contains no items.
134
    ///
135
    /// # Examples
136
    ///
137
    /// ```
138
    /// assert!(!(3..5).is_empty());
139
    /// assert!( (3..3).is_empty());
140
    /// assert!( (3..2).is_empty());
141
    /// ```
142
    ///
143
    /// The range is empty if either side is incomparable:
144
    ///
145
    /// ```
146
    /// assert!(!(3.0..5.0).is_empty());
147
    /// assert!( (3.0..f32::NAN).is_empty());
148
    /// assert!( (f32::NAN..5.0).is_empty());
149
    /// ```
150
    #[inline]
151
    #[stable(feature = "range_is_empty", since = "1.47.0")]
152
    pub fn is_empty(&self) -> bool {
153
        !(self.start < self.end)
154
    }
155
}
156

            
157
/// A range only bounded inclusively below (`start..`).
158
///
159
/// The `RangeFrom` `start..` contains all values with `x >= start`.
160
///
161
/// *Note*: Overflow in the [`Iterator`] implementation (when the contained
162
/// data type reaches its numerical limit) is allowed to panic, wrap, or
163
/// saturate. This behavior is defined by the implementation of the [`Step`]
164
/// trait. For primitive integers, this follows the normal rules, and respects
165
/// the overflow checks profile (panic in debug, wrap in release). Note also
166
/// that overflow happens earlier than you might assume: the overflow happens
167
/// in the call to `next` that yields the maximum value, as the range must be
168
/// set to a state to yield the next value.
169
///
170
/// [`Step`]: crate::iter::Step
171
///
172
/// # Examples
173
///
174
/// The `start..` syntax is a `RangeFrom`:
175
///
176
/// ```
177
/// assert_eq!((2..), std::ops::RangeFrom { start: 2 });
178
/// assert_eq!(2 + 3 + 4, (2..).take(3).sum());
179
/// ```
180
///
181
/// ```
182
/// let arr = [0, 1, 2, 3, 4];
183
/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
184
/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
185
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
186
/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]); // This is a `RangeFrom`
187
/// assert_eq!(arr[1.. 3], [   1, 2      ]);
188
/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
189
/// ```
190
#[lang = "RangeFrom"]
191
#[doc(alias = "..")]
192
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Clone, PartialEq, Eq, Hash))] // not Copy -- see #27186
193
#[stable(feature = "rust1", since = "1.0.0")]
194
pub struct RangeFrom<Idx> {
195
    /// The lower bound of the range (inclusive).
196
    #[stable(feature = "rust1", since = "1.0.0")]
197
    pub start: Idx,
198
}
199

            
200
#[stable(feature = "rust1", since = "1.0.0")]
201
#[cfg(not(feature = "ferrocene_certified"))]
202
impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
203
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
204
        self.start.fmt(fmt)?;
205
        write!(fmt, "..")?;
206
        Ok(())
207
    }
208
}
209

            
210
#[cfg(not(feature = "ferrocene_certified"))]
211
impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
212
    /// Returns `true` if `item` is contained in the range.
213
    ///
214
    /// # Examples
215
    ///
216
    /// ```
217
    /// assert!(!(3..).contains(&2));
218
    /// assert!( (3..).contains(&3));
219
    /// assert!( (3..).contains(&1_000_000_000));
220
    ///
221
    /// assert!( (0.0..).contains(&0.5));
222
    /// assert!(!(0.0..).contains(&f32::NAN));
223
    /// assert!(!(f32::NAN..).contains(&0.5));
224
    /// ```
225
    #[inline]
226
    #[stable(feature = "range_contains", since = "1.35.0")]
227
    pub fn contains<U>(&self, item: &U) -> bool
228
    where
229
        Idx: PartialOrd<U>,
230
        U: ?Sized + PartialOrd<Idx>,
231
    {
232
        <Self as RangeBounds<Idx>>::contains(self, item)
233
    }
234
}
235

            
236
/// A range only bounded exclusively above (`..end`).
237
///
238
/// The `RangeTo` `..end` contains all values with `x < end`.
239
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
240
///
241
/// # Examples
242
///
243
/// The `..end` syntax is a `RangeTo`:
244
///
245
/// ```
246
/// assert_eq!((..5), std::ops::RangeTo { end: 5 });
247
/// ```
248
///
249
/// It does not have an [`IntoIterator`] implementation, so you can't use it in
250
/// a `for` loop directly. This won't compile:
251
///
252
/// ```compile_fail,E0277
253
/// // error[E0277]: the trait bound `std::ops::RangeTo<{integer}>:
254
/// // std::iter::Iterator` is not satisfied
255
/// for i in ..5 {
256
///     // ...
257
/// }
258
/// ```
259
///
260
/// When used as a [slicing index], `RangeTo` produces a slice of all array
261
/// elements before the index indicated by `end`.
262
///
263
/// ```
264
/// let arr = [0, 1, 2, 3, 4];
265
/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
266
/// assert_eq!(arr[ .. 3], [0, 1, 2      ]); // This is a `RangeTo`
267
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
268
/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
269
/// assert_eq!(arr[1.. 3], [   1, 2      ]);
270
/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
271
/// ```
272
///
273
/// [slicing index]: crate::slice::SliceIndex
274
#[lang = "RangeTo"]
275
#[doc(alias = "..")]
276
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Clone, PartialEq, Eq, Hash))]
277
#[stable(feature = "rust1", since = "1.0.0")]
278
pub struct RangeTo<Idx> {
279
    /// The upper bound of the range (exclusive).
280
    #[stable(feature = "rust1", since = "1.0.0")]
281
    pub end: Idx,
282
}
283

            
284
#[stable(feature = "rust1", since = "1.0.0")]
285
#[cfg(not(feature = "ferrocene_certified"))]
286
impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
287
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
288
        write!(fmt, "..")?;
289
        self.end.fmt(fmt)?;
290
        Ok(())
291
    }
292
}
293

            
294
#[cfg(not(feature = "ferrocene_certified"))]
295
impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
296
    /// Returns `true` if `item` is contained in the range.
297
    ///
298
    /// # Examples
299
    ///
300
    /// ```
301
    /// assert!( (..5).contains(&-1_000_000_000));
302
    /// assert!( (..5).contains(&4));
303
    /// assert!(!(..5).contains(&5));
304
    ///
305
    /// assert!( (..1.0).contains(&0.5));
306
    /// assert!(!(..1.0).contains(&f32::NAN));
307
    /// assert!(!(..f32::NAN).contains(&0.5));
308
    /// ```
309
    #[inline]
310
    #[stable(feature = "range_contains", since = "1.35.0")]
311
    pub fn contains<U>(&self, item: &U) -> bool
312
    where
313
        Idx: PartialOrd<U>,
314
        U: ?Sized + PartialOrd<Idx>,
315
    {
316
        <Self as RangeBounds<Idx>>::contains(self, item)
317
    }
318
}
319

            
320
/// A range bounded inclusively below and above (`start..=end`).
321
///
322
/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
323
/// and `x <= end`. It is empty unless `start <= end`.
324
///
325
/// This iterator is [fused], but the specific values of `start` and `end` after
326
/// iteration has finished are **unspecified** other than that [`.is_empty()`]
327
/// will return `true` once no more values will be produced.
328
///
329
/// [fused]: crate::iter::FusedIterator
330
/// [`.is_empty()`]: RangeInclusive::is_empty
331
///
332
/// # Examples
333
///
334
/// The `start..=end` syntax is a `RangeInclusive`:
335
///
336
/// ```
337
/// assert_eq!((3..=5), std::ops::RangeInclusive::new(3, 5));
338
/// assert_eq!(3 + 4 + 5, (3..=5).sum());
339
/// ```
340
///
341
/// ```
342
/// let arr = [0, 1, 2, 3, 4];
343
/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
344
/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
345
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
346
/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
347
/// assert_eq!(arr[1.. 3], [   1, 2      ]);
348
/// assert_eq!(arr[1..=3], [   1, 2, 3   ]); // This is a `RangeInclusive`
349
/// ```
350
#[lang = "RangeInclusive"]
351
#[doc(alias = "..=")]
352
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Clone, PartialEq, Eq, Hash))] // not Copy -- see #27186
353
#[stable(feature = "inclusive_range", since = "1.26.0")]
354
pub struct RangeInclusive<Idx> {
355
    // Note that the fields here are not public to allow changing the
356
    // representation in the future; in particular, while we could plausibly
357
    // expose start/end, modifying them without changing (future/current)
358
    // private fields may lead to incorrect behavior, so we don't want to
359
    // support that mode.
360
    pub(crate) start: Idx,
361
    pub(crate) end: Idx,
362

            
363
    // This field is:
364
    //  - `false` upon construction
365
    //  - `false` when iteration has yielded an element and the iterator is not exhausted
366
    //  - `true` when iteration has been used to exhaust the iterator
367
    //
368
    // This is required to support PartialEq and Hash without a PartialOrd bound or specialization.
369
    pub(crate) exhausted: bool,
370
}
371

            
372
impl<Idx> RangeInclusive<Idx> {
373
    /// Creates a new inclusive range. Equivalent to writing `start..=end`.
374
    ///
375
    /// # Examples
376
    ///
377
    /// ```
378
    /// use std::ops::RangeInclusive;
379
    ///
380
    /// assert_eq!(3..=5, RangeInclusive::new(3, 5));
381
    /// ```
382
    #[lang = "range_inclusive_new"]
383
    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
384
    #[inline]
385
    #[rustc_promotable]
386
    #[rustc_const_stable(feature = "const_range_new", since = "1.32.0")]
387
1940
    pub const fn new(start: Idx, end: Idx) -> Self {
388
1940
        Self { start, end, exhausted: false }
389
1940
    }
390

            
391
    /// Returns the lower bound of the range (inclusive).
392
    ///
393
    /// When using an inclusive range for iteration, the values of `start()` and
394
    /// [`end()`] are unspecified after the iteration ended. To determine
395
    /// whether the inclusive range is empty, use the [`is_empty()`] method
396
    /// instead of comparing `start() > end()`.
397
    ///
398
    /// Note: the value returned by this method is unspecified after the range
399
    /// has been iterated to exhaustion.
400
    ///
401
    /// [`end()`]: RangeInclusive::end
402
    /// [`is_empty()`]: RangeInclusive::is_empty
403
    ///
404
    /// # Examples
405
    ///
406
    /// ```
407
    /// assert_eq!((3..=5).start(), &3);
408
    /// ```
409
    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
410
    #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
411
    #[inline]
412
3584
    pub const fn start(&self) -> &Idx {
413
3584
        &self.start
414
3584
    }
415

            
416
    /// Returns the upper bound of the range (inclusive).
417
    ///
418
    /// When using an inclusive range for iteration, the values of [`start()`]
419
    /// and `end()` are unspecified after the iteration ended. To determine
420
    /// whether the inclusive range is empty, use the [`is_empty()`] method
421
    /// instead of comparing `start() > end()`.
422
    ///
423
    /// Note: the value returned by this method is unspecified after the range
424
    /// has been iterated to exhaustion.
425
    ///
426
    /// [`start()`]: RangeInclusive::start
427
    /// [`is_empty()`]: RangeInclusive::is_empty
428
    ///
429
    /// # Examples
430
    ///
431
    /// ```
432
    /// assert_eq!((3..=5).end(), &5);
433
    /// ```
434
    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
435
    #[rustc_const_stable(feature = "const_inclusive_range_methods", since = "1.32.0")]
436
    #[inline]
437
3584
    pub const fn end(&self) -> &Idx {
438
3584
        &self.end
439
3584
    }
440

            
441
    /// Destructures the `RangeInclusive` into (lower bound, upper (inclusive) bound).
442
    ///
443
    /// Note: the value returned by this method is unspecified after the range
444
    /// has been iterated to exhaustion.
445
    ///
446
    /// # Examples
447
    ///
448
    /// ```
449
    /// assert_eq!((3..=5).into_inner(), (3, 5));
450
    /// ```
451
    #[stable(feature = "inclusive_range_methods", since = "1.27.0")]
452
    #[inline]
453
    #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")]
454
    #[cfg(not(feature = "ferrocene_certified"))]
455
    pub const fn into_inner(self) -> (Idx, Idx) {
456
        (self.start, self.end)
457
    }
458
}
459

            
460
#[cfg(not(feature = "ferrocene_certified"))]
461
impl RangeInclusive<usize> {
462
    /// Converts to an exclusive `Range` for `SliceIndex` implementations.
463
    /// The caller is responsible for dealing with `end == usize::MAX`.
464
    #[inline]
465
    pub(crate) const fn into_slice_range(self) -> Range<usize> {
466
        // If we're not exhausted, we want to simply slice `start..end + 1`.
467
        // If we are exhausted, then slicing with `end + 1..end + 1` gives us an
468
        // empty range that is still subject to bounds-checks for that endpoint.
469
        let exclusive_end = self.end + 1;
470
        let start = if self.exhausted { exclusive_end } else { self.start };
471
        start..exclusive_end
472
    }
473
}
474

            
475
#[stable(feature = "inclusive_range", since = "1.26.0")]
476
#[cfg(not(feature = "ferrocene_certified"))]
477
impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
478
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
479
        self.start.fmt(fmt)?;
480
        write!(fmt, "..=")?;
481
        self.end.fmt(fmt)?;
482
        if self.exhausted {
483
            write!(fmt, " (exhausted)")?;
484
        }
485
        Ok(())
486
    }
487
}
488

            
489
#[cfg(not(feature = "ferrocene_certified"))]
490
impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
491
    /// Returns `true` if `item` is contained in the range.
492
    ///
493
    /// # Examples
494
    ///
495
    /// ```
496
    /// assert!(!(3..=5).contains(&2));
497
    /// assert!( (3..=5).contains(&3));
498
    /// assert!( (3..=5).contains(&4));
499
    /// assert!( (3..=5).contains(&5));
500
    /// assert!(!(3..=5).contains(&6));
501
    ///
502
    /// assert!( (3..=3).contains(&3));
503
    /// assert!(!(3..=2).contains(&3));
504
    ///
505
    /// assert!( (0.0..=1.0).contains(&1.0));
506
    /// assert!(!(0.0..=1.0).contains(&f32::NAN));
507
    /// assert!(!(0.0..=f32::NAN).contains(&0.0));
508
    /// assert!(!(f32::NAN..=1.0).contains(&1.0));
509
    /// ```
510
    ///
511
    /// This method always returns `false` after iteration has finished:
512
    ///
513
    /// ```
514
    /// let mut r = 3..=5;
515
    /// assert!(r.contains(&3) && r.contains(&5));
516
    /// for _ in r.by_ref() {}
517
    /// // Precise field values are unspecified here
518
    /// assert!(!r.contains(&3) && !r.contains(&5));
519
    /// ```
520
    #[inline]
521
    #[stable(feature = "range_contains", since = "1.35.0")]
522
    pub fn contains<U>(&self, item: &U) -> bool
523
    where
524
        Idx: PartialOrd<U>,
525
        U: ?Sized + PartialOrd<Idx>,
526
    {
527
        <Self as RangeBounds<Idx>>::contains(self, item)
528
    }
529

            
530
    /// Returns `true` if the range contains no items.
531
    ///
532
    /// # Examples
533
    ///
534
    /// ```
535
    /// assert!(!(3..=5).is_empty());
536
    /// assert!(!(3..=3).is_empty());
537
    /// assert!( (3..=2).is_empty());
538
    /// ```
539
    ///
540
    /// The range is empty if either side is incomparable:
541
    ///
542
    /// ```
543
    /// assert!(!(3.0..=5.0).is_empty());
544
    /// assert!( (3.0..=f32::NAN).is_empty());
545
    /// assert!( (f32::NAN..=5.0).is_empty());
546
    /// ```
547
    ///
548
    /// This method returns `true` after iteration has finished:
549
    ///
550
    /// ```
551
    /// let mut r = 3..=5;
552
    /// for _ in r.by_ref() {}
553
    /// // Precise field values are unspecified here
554
    /// assert!(r.is_empty());
555
    /// ```
556
    #[stable(feature = "range_is_empty", since = "1.47.0")]
557
    #[inline]
558
6978
    pub fn is_empty(&self) -> bool {
559
6978
        self.exhausted || !(self.start <= self.end)
560
6978
    }
561
}
562

            
563
/// A range only bounded inclusively above (`..=end`).
564
///
565
/// The `RangeToInclusive` `..=end` contains all values with `x <= end`.
566
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
567
///
568
/// # Examples
569
///
570
/// The `..=end` syntax is a `RangeToInclusive`:
571
///
572
/// ```
573
/// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 });
574
/// ```
575
///
576
/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
577
/// `for` loop directly. This won't compile:
578
///
579
/// ```compile_fail,E0277
580
/// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
581
/// // std::iter::Iterator` is not satisfied
582
/// for i in ..=5 {
583
///     // ...
584
/// }
585
/// ```
586
///
587
/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
588
/// array elements up to and including the index indicated by `end`.
589
///
590
/// ```
591
/// let arr = [0, 1, 2, 3, 4];
592
/// assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
593
/// assert_eq!(arr[ .. 3], [0, 1, 2      ]);
594
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]); // This is a `RangeToInclusive`
595
/// assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
596
/// assert_eq!(arr[1.. 3], [   1, 2      ]);
597
/// assert_eq!(arr[1..=3], [   1, 2, 3   ]);
598
/// ```
599
///
600
/// [slicing index]: crate::slice::SliceIndex
601
#[lang = "RangeToInclusive"]
602
#[doc(alias = "..=")]
603
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Clone, PartialEq, Eq, Hash))]
604
#[stable(feature = "inclusive_range", since = "1.26.0")]
605
pub struct RangeToInclusive<Idx> {
606
    /// The upper bound of the range (inclusive)
607
    #[stable(feature = "inclusive_range", since = "1.26.0")]
608
    pub end: Idx,
609
}
610

            
611
#[stable(feature = "inclusive_range", since = "1.26.0")]
612
#[cfg(not(feature = "ferrocene_certified"))]
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
#[cfg(not(feature = "ferrocene_certified"))]
622
impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
623
    /// Returns `true` if `item` is contained in the range.
624
    ///
625
    /// # Examples
626
    ///
627
    /// ```
628
    /// assert!( (..=5).contains(&-1_000_000_000));
629
    /// assert!( (..=5).contains(&5));
630
    /// assert!(!(..=5).contains(&6));
631
    ///
632
    /// assert!( (..=1.0).contains(&1.0));
633
    /// assert!(!(..=1.0).contains(&f32::NAN));
634
    /// assert!(!(..=f32::NAN).contains(&0.5));
635
    /// ```
636
    #[inline]
637
    #[stable(feature = "range_contains", since = "1.35.0")]
638
    pub fn contains<U>(&self, item: &U) -> bool
639
    where
640
        Idx: PartialOrd<U>,
641
        U: ?Sized + PartialOrd<Idx>,
642
    {
643
        <Self as RangeBounds<Idx>>::contains(self, item)
644
    }
645
}
646

            
647
// RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
648
// because underflow would be possible with (..0).into()
649

            
650
/// An endpoint of a range of keys.
651
///
652
/// # Examples
653
///
654
/// `Bound`s are range endpoints:
655
///
656
/// ```
657
/// use std::ops::Bound::*;
658
/// use std::ops::RangeBounds;
659
///
660
/// assert_eq!((..100).start_bound(), Unbounded);
661
/// assert_eq!((1..12).start_bound(), Included(&1));
662
/// assert_eq!((1..12).end_bound(), Excluded(&12));
663
/// ```
664
///
665
/// Using a tuple of `Bound`s as an argument to [`BTreeMap::range`].
666
/// Note that in most cases, it's better to use range syntax (`1..5`) instead.
667
///
668
/// ```
669
/// use std::collections::BTreeMap;
670
/// use std::ops::Bound::{Excluded, Included, Unbounded};
671
///
672
/// let mut map = BTreeMap::new();
673
/// map.insert(3, "a");
674
/// map.insert(5, "b");
675
/// map.insert(8, "c");
676
///
677
/// for (key, value) in map.range((Excluded(3), Included(8))) {
678
///     println!("{key}: {value}");
679
/// }
680
///
681
/// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());
682
/// ```
683
///
684
/// [`BTreeMap::range`]: ../../std/collections/btree_map/struct.BTreeMap.html#method.range
685
#[stable(feature = "collections_bound", since = "1.17.0")]
686
#[cfg_attr(not(feature = "ferrocene_certified"), derive(Clone, Copy, Debug, Hash, PartialEq, Eq))]
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
impl<T> Bound<T> {
700
    /// Converts from `&Bound<T>` to `Bound<&T>`.
701
    #[inline]
702
    #[stable(feature = "bound_as_ref_shared", since = "1.65.0")]
703
    pub fn as_ref(&self) -> Bound<&T> {
704
        match *self {
705
            Included(ref x) => Included(x),
706
            Excluded(ref x) => Excluded(x),
707
            Unbounded => Unbounded,
708
        }
709
    }
710

            
711
    /// Converts from `&mut Bound<T>` to `Bound<&mut T>`.
712
    #[inline]
713
    #[unstable(feature = "bound_as_ref", issue = "80996")]
714
    pub fn as_mut(&mut self) -> Bound<&mut T> {
715
        match *self {
716
            Included(ref mut x) => Included(x),
717
            Excluded(ref mut x) => Excluded(x),
718
            Unbounded => Unbounded,
719
        }
720
    }
721

            
722
    /// Maps a `Bound<T>` to a `Bound<U>` by applying a function to the contained value (including
723
    /// both `Included` and `Excluded`), returning a `Bound` of the same kind.
724
    ///
725
    /// # Examples
726
    ///
727
    /// ```
728
    /// use std::ops::Bound::*;
729
    ///
730
    /// let bound_string = Included("Hello, World!");
731
    ///
732
    /// assert_eq!(bound_string.map(|s| s.len()), Included(13));
733
    /// ```
734
    ///
735
    /// ```
736
    /// use std::ops::Bound;
737
    /// use Bound::*;
738
    ///
739
    /// let unbounded_string: Bound<String> = Unbounded;
740
    ///
741
    /// assert_eq!(unbounded_string.map(|s| s.len()), Unbounded);
742
    /// ```
743
    #[inline]
744
    #[stable(feature = "bound_map", since = "1.77.0")]
745
    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Bound<U> {
746
        match self {
747
            Unbounded => Unbounded,
748
            Included(x) => Included(f(x)),
749
            Excluded(x) => Excluded(f(x)),
750
        }
751
    }
752
}
753

            
754
impl<T: Copy> Bound<&T> {
755
    /// Map a `Bound<&T>` to a `Bound<T>` by copying the contents of the bound.
756
    ///
757
    /// # Examples
758
    ///
759
    /// ```
760
    /// #![feature(bound_copied)]
761
    ///
762
    /// use std::ops::Bound::*;
763
    /// use std::ops::RangeBounds;
764
    ///
765
    /// assert_eq!((1..12).start_bound(), Included(&1));
766
    /// assert_eq!((1..12).start_bound().copied(), Included(1));
767
    /// ```
768
    #[unstable(feature = "bound_copied", issue = "145966")]
769
    #[must_use]
770
    pub fn copied(self) -> Bound<T> {
771
        match self {
772
            Bound::Unbounded => Bound::Unbounded,
773
            Bound::Included(x) => Bound::Included(*x),
774
            Bound::Excluded(x) => Bound::Excluded(*x),
775
        }
776
    }
777
}
778

            
779
impl<T: Clone> Bound<&T> {
780
    /// Map a `Bound<&T>` to a `Bound<T>` by cloning the contents of the bound.
781
    ///
782
    /// # Examples
783
    ///
784
    /// ```
785
    /// use std::ops::Bound::*;
786
    /// use std::ops::RangeBounds;
787
    ///
788
    /// let a1 = String::from("a");
789
    /// let (a2, a3, a4) = (a1.clone(), a1.clone(), a1.clone());
790
    ///
791
    /// assert_eq!(Included(&a1), (a2..).start_bound());
792
    /// assert_eq!(Included(a3), (a4..).start_bound().cloned());
793
    /// ```
794
    #[must_use = "`self` will be dropped if the result is not used"]
795
    #[stable(feature = "bound_cloned", since = "1.55.0")]
796
    pub fn cloned(self) -> Bound<T> {
797
        match self {
798
            Bound::Unbounded => Bound::Unbounded,
799
            Bound::Included(x) => Bound::Included(x.clone()),
800
            Bound::Excluded(x) => Bound::Excluded(x.clone()),
801
        }
802
    }
803
}
804

            
805
/// `RangeBounds` is implemented by Rust's built-in range types, produced
806
/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
807
#[stable(feature = "collections_range", since = "1.28.0")]
808
#[rustc_diagnostic_item = "RangeBounds"]
809
pub trait RangeBounds<T: ?Sized> {
810
    /// Start index bound.
811
    ///
812
    /// Returns the start value as a `Bound`.
813
    ///
814
    /// # Examples
815
    ///
816
    /// ```
817
    /// use std::ops::Bound::*;
818
    /// use std::ops::RangeBounds;
819
    ///
820
    /// assert_eq!((..10).start_bound(), Unbounded);
821
    /// assert_eq!((3..10).start_bound(), Included(&3));
822
    /// ```
823
    #[stable(feature = "collections_range", since = "1.28.0")]
824
    fn start_bound(&self) -> Bound<&T>;
825

            
826
    /// End index bound.
827
    ///
828
    /// Returns the end value as a `Bound`.
829
    ///
830
    /// # Examples
831
    ///
832
    /// ```
833
    /// use std::ops::Bound::*;
834
    /// use std::ops::RangeBounds;
835
    ///
836
    /// assert_eq!((3..).end_bound(), Unbounded);
837
    /// assert_eq!((3..10).end_bound(), Excluded(&10));
838
    /// ```
839
    #[stable(feature = "collections_range", since = "1.28.0")]
840
    fn end_bound(&self) -> Bound<&T>;
841

            
842
    /// Returns `true` if `item` is contained in the range.
843
    ///
844
    /// # Examples
845
    ///
846
    /// ```
847
    /// assert!( (3..5).contains(&4));
848
    /// assert!(!(3..5).contains(&2));
849
    ///
850
    /// assert!( (0.0..1.0).contains(&0.5));
851
    /// assert!(!(0.0..1.0).contains(&f32::NAN));
852
    /// assert!(!(0.0..f32::NAN).contains(&0.5));
853
    /// assert!(!(f32::NAN..1.0).contains(&0.5));
854
    /// ```
855
    #[inline]
856
    #[stable(feature = "range_contains", since = "1.35.0")]
857
    #[cfg(not(feature = "ferrocene_certified"))]
858
    fn contains<U>(&self, item: &U) -> bool
859
    where
860
        T: PartialOrd<U>,
861
        U: ?Sized + PartialOrd<T>,
862
    {
863
        (match self.start_bound() {
864
            Included(start) => start <= item,
865
            Excluded(start) => start < item,
866
            Unbounded => true,
867
        }) && (match self.end_bound() {
868
            Included(end) => item <= end,
869
            Excluded(end) => item < end,
870
            Unbounded => true,
871
        })
872
    }
873

            
874
    /// Returns `true` if the range contains no items.
875
    /// One-sided ranges (`RangeFrom`, etc) always return `false`.
876
    ///
877
    /// # Examples
878
    ///
879
    /// ```
880
    /// #![feature(range_bounds_is_empty)]
881
    /// use std::ops::RangeBounds;
882
    ///
883
    /// assert!(!(3..).is_empty());
884
    /// assert!(!(..2).is_empty());
885
    /// assert!(!RangeBounds::is_empty(&(3..5)));
886
    /// assert!( RangeBounds::is_empty(&(3..3)));
887
    /// assert!( RangeBounds::is_empty(&(3..2)));
888
    /// ```
889
    ///
890
    /// The range is empty if either side is incomparable:
891
    ///
892
    /// ```
893
    /// #![feature(range_bounds_is_empty)]
894
    /// use std::ops::RangeBounds;
895
    ///
896
    /// assert!(!RangeBounds::is_empty(&(3.0..5.0)));
897
    /// assert!( RangeBounds::is_empty(&(3.0..f32::NAN)));
898
    /// assert!( RangeBounds::is_empty(&(f32::NAN..5.0)));
899
    /// ```
900
    ///
901
    /// But never empty if either side is unbounded:
902
    ///
903
    /// ```
904
    /// #![feature(range_bounds_is_empty)]
905
    /// use std::ops::RangeBounds;
906
    ///
907
    /// assert!(!(..0).is_empty());
908
    /// assert!(!(i32::MAX..).is_empty());
909
    /// assert!(!RangeBounds::<u8>::is_empty(&(..)));
910
    /// ```
911
    ///
912
    /// `(Excluded(a), Excluded(b))` is only empty if `a >= b`:
913
    ///
914
    /// ```
915
    /// #![feature(range_bounds_is_empty)]
916
    /// use std::ops::Bound::*;
917
    /// use std::ops::RangeBounds;
918
    ///
919
    /// assert!(!(Excluded(1), Excluded(3)).is_empty());
920
    /// assert!(!(Excluded(1), Excluded(2)).is_empty());
921
    /// assert!( (Excluded(1), Excluded(1)).is_empty());
922
    /// assert!( (Excluded(2), Excluded(1)).is_empty());
923
    /// assert!( (Excluded(3), Excluded(1)).is_empty());
924
    /// ```
925
    #[unstable(feature = "range_bounds_is_empty", issue = "137300")]
926
    #[cfg(not(feature = "ferrocene_certified"))]
927
    fn is_empty(&self) -> bool
928
    where
929
        T: PartialOrd,
930
    {
931
        !match (self.start_bound(), self.end_bound()) {
932
            (Unbounded, _) | (_, Unbounded) => true,
933
            (Included(start), Excluded(end))
934
            | (Excluded(start), Included(end))
935
            | (Excluded(start), Excluded(end)) => start < end,
936
            (Included(start), Included(end)) => start <= end,
937
        }
938
    }
939
}
940

            
941
/// Used to convert a range into start and end bounds, consuming the
942
/// range by value.
943
///
944
/// `IntoBounds` is implemented by Rust’s built-in range types, produced
945
/// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`.
946
#[unstable(feature = "range_into_bounds", issue = "136903")]
947
pub trait IntoBounds<T>: RangeBounds<T> {
948
    /// Convert this range into the start and end bounds.
949
    /// Returns `(start_bound, end_bound)`.
950
    ///
951
    /// # Examples
952
    ///
953
    /// ```
954
    /// #![feature(range_into_bounds)]
955
    /// use std::ops::Bound::*;
956
    /// use std::ops::IntoBounds;
957
    ///
958
    /// assert_eq!((0..5).into_bounds(), (Included(0), Excluded(5)));
959
    /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7)));
960
    /// ```
961
    fn into_bounds(self) -> (Bound<T>, Bound<T>);
962

            
963
    /// Compute the intersection of  `self` and `other`.
964
    ///
965
    /// # Examples
966
    ///
967
    /// ```
968
    /// #![feature(range_into_bounds)]
969
    /// use std::ops::Bound::*;
970
    /// use std::ops::IntoBounds;
971
    ///
972
    /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5)));
973
    /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256)));
974
    /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5)));
975
    /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9)));
976
    /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13)));
977
    /// ```
978
    ///
979
    /// Combine with `is_empty` to determine if two ranges overlap.
980
    ///
981
    /// ```
982
    /// #![feature(range_into_bounds)]
983
    /// #![feature(range_bounds_is_empty)]
984
    /// use std::ops::{RangeBounds, IntoBounds};
985
    ///
986
    /// assert!(!(3..).intersect(..5).is_empty());
987
    /// assert!(!(-12..387).intersect(0..256).is_empty());
988
    /// assert!((1..5).intersect(6..).is_empty());
989
    /// ```
990
    #[cfg(not(feature = "ferrocene_certified"))]
991
    fn intersect<R>(self, other: R) -> (Bound<T>, Bound<T>)
992
    where
993
        Self: Sized,
994
        T: Ord,
995
        R: Sized + IntoBounds<T>,
996
    {
997
        let (self_start, self_end) = IntoBounds::into_bounds(self);
998
        let (other_start, other_end) = IntoBounds::into_bounds(other);
999

            
        let start = match (self_start, other_start) {
            (Included(a), Included(b)) => Included(Ord::max(a, b)),
            (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)),
            (Unbounded, Unbounded) => Unbounded,
            (x, Unbounded) | (Unbounded, x) => x,
            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
                if i > e {
                    Included(i)
                } else {
                    Excluded(e)
                }
            }
        };
        let end = match (self_end, other_end) {
            (Included(a), Included(b)) => Included(Ord::min(a, b)),
            (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)),
            (Unbounded, Unbounded) => Unbounded,
            (x, Unbounded) | (Unbounded, x) => x,
            (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
                if i < e {
                    Included(i)
                } else {
                    Excluded(e)
                }
            }
        };
        (start, end)
    }
}
use self::Bound::{Excluded, Included, Unbounded};
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T: ?Sized> RangeBounds<T> for RangeFull {
1373
    fn start_bound(&self) -> Bound<&T> {
1373
        Unbounded
1373
    }
1373
    fn end_bound(&self) -> Bound<&T> {
1373
        Unbounded
1373
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for RangeFull {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        (Unbounded, Unbounded)
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeFrom<T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(&self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        Unbounded
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for RangeFrom<T> {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        (Included(self.start), Unbounded)
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeTo<T> {
    fn start_bound(&self) -> Bound<&T> {
        Unbounded
    }
    fn end_bound(&self) -> Bound<&T> {
        Excluded(&self.end)
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for RangeTo<T> {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        (Unbounded, Excluded(self.end))
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for Range<T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(&self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        Excluded(&self.end)
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for Range<T> {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        (Included(self.start), Excluded(self.end))
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeInclusive<T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(&self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        if self.exhausted {
            // When the iterator is exhausted, we usually have start == end,
            // but we want the range to appear empty, containing nothing.
            Excluded(&self.end)
        } else {
            Included(&self.end)
        }
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for RangeInclusive<T> {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        (
            Included(self.start),
            if self.exhausted {
                // When the iterator is exhausted, we usually have start == end,
                // but we want the range to appear empty, containing nothing.
                Excluded(self.end)
            } else {
                Included(self.end)
            },
        )
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeToInclusive<T> {
    fn start_bound(&self) -> Bound<&T> {
        Unbounded
    }
    fn end_bound(&self) -> Bound<&T> {
        Included(&self.end)
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for RangeToInclusive<T> {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        (Unbounded, Included(self.end))
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for (Bound<T>, Bound<T>) {
    fn start_bound(&self) -> Bound<&T> {
        match *self {
            (Included(ref start), _) => Included(start),
            (Excluded(ref start), _) => Excluded(start),
            (Unbounded, _) => Unbounded,
        }
    }
    fn end_bound(&self) -> Bound<&T> {
        match *self {
            (_, Included(ref end)) => Included(end),
            (_, Excluded(ref end)) => Excluded(end),
            (_, Unbounded) => Unbounded,
        }
    }
}
#[unstable(feature = "range_into_bounds", issue = "136903")]
impl<T> IntoBounds<T> for (Bound<T>, Bound<T>) {
    fn into_bounds(self) -> (Bound<T>, Bound<T>) {
        self
    }
}
#[stable(feature = "collections_range", since = "1.28.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a, T: ?Sized + 'a> RangeBounds<T> for (Bound<&'a T>, Bound<&'a T>) {
    fn start_bound(&self) -> Bound<&T> {
        self.0
    }
    fn end_bound(&self) -> Bound<&T> {
        self.1
    }
}
// This impl intentionally does not have `T: ?Sized`;
// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
//
/// If you need to use this implementation where `T` is unsized,
/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`.
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeFrom<&T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        Unbounded
    }
}
// This impl intentionally does not have `T: ?Sized`;
// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
//
/// If you need to use this implementation where `T` is unsized,
/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
/// i.e. replace `..end` with `(Bound::Unbounded, Bound::Excluded(end))`.
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeTo<&T> {
    fn start_bound(&self) -> Bound<&T> {
        Unbounded
    }
    fn end_bound(&self) -> Bound<&T> {
        Excluded(self.end)
    }
}
// This impl intentionally does not have `T: ?Sized`;
// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
//
/// If you need to use this implementation where `T` is unsized,
/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`.
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for Range<&T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        Excluded(self.end)
    }
}
// This impl intentionally does not have `T: ?Sized`;
// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
//
/// If you need to use this implementation where `T` is unsized,
/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`.
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeInclusive<&T> {
    fn start_bound(&self) -> Bound<&T> {
        Included(self.start)
    }
    fn end_bound(&self) -> Bound<&T> {
        Included(self.end)
    }
}
// This impl intentionally does not have `T: ?Sized`;
// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
//
/// If you need to use this implementation where `T` is unsized,
/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
/// i.e. replace `..=end` with `(Bound::Unbounded, Bound::Included(end))`.
#[stable(feature = "collections_range", since = "1.28.0")]
impl<T> RangeBounds<T> for RangeToInclusive<&T> {
    fn start_bound(&self) -> Bound<&T> {
        Unbounded
    }
    fn end_bound(&self) -> Bound<&T> {
        Included(self.end)
    }
}
/// An internal helper for `split_off` functions indicating
/// which end a `OneSidedRange` is bounded on.
#[unstable(feature = "one_sided_range", issue = "69780")]
#[allow(missing_debug_implementations)]
pub enum OneSidedRangeBound {
    /// The range is bounded inclusively from below and is unbounded above.
    StartInclusive,
    /// The range is bounded exclusively from above and is unbounded below.
    End,
    /// The range is bounded inclusively from above and is unbounded below.
    EndInclusive,
}
/// `OneSidedRange` is implemented for built-in range types that are unbounded
/// on one side. For example, `a..`, `..b` and `..=c` implement `OneSidedRange`,
/// but `..`, `d..e`, and `f..=g` do not.
///
/// Types that implement `OneSidedRange<T>` must return `Bound::Unbounded`
/// from one of `RangeBounds::start_bound` or `RangeBounds::end_bound`.
#[unstable(feature = "one_sided_range", issue = "69780")]
pub trait OneSidedRange<T>: RangeBounds<T> {
    /// An internal-only helper function for `split_off` and
    /// `split_off_mut` that returns the bound of the one-sided range.
    fn bound(self) -> (OneSidedRangeBound, T);
}
#[unstable(feature = "one_sided_range", issue = "69780")]
impl<T> OneSidedRange<T> for RangeTo<T>
where
    Self: RangeBounds<T>,
{
    fn bound(self) -> (OneSidedRangeBound, T) {
        (OneSidedRangeBound::End, self.end)
    }
}
#[unstable(feature = "one_sided_range", issue = "69780")]
impl<T> OneSidedRange<T> for RangeFrom<T>
where
    Self: RangeBounds<T>,
{
    fn bound(self) -> (OneSidedRangeBound, T) {
        (OneSidedRangeBound::StartInclusive, self.start)
    }
}
#[unstable(feature = "one_sided_range", issue = "69780")]
impl<T> OneSidedRange<T> for RangeToInclusive<T>
where
    Self: RangeBounds<T>,
{
    fn bound(self) -> (OneSidedRangeBound, T) {
        (OneSidedRangeBound::EndInclusive, self.end)
    }
}