core/range.rs
1//! # Replacement range types
2//!
3//! The types within this module are meant to replace the legacy `Range`,
4//! `RangeInclusive`, `RangeToInclusive` and `RangeFrom` types in a future edition.
5//!
6//! ```
7//! use core::range::{Range, RangeFrom, RangeInclusive, RangeToInclusive};
8//!
9//! let arr = [0, 1, 2, 3, 4];
10//! assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
11//! assert_eq!(arr[ .. 3 ], [0, 1, 2 ]);
12//! assert_eq!(arr[RangeToInclusive::from( ..=3)], [0, 1, 2, 3 ]);
13//! assert_eq!(arr[ RangeFrom::from(1.. )], [ 1, 2, 3, 4]);
14//! assert_eq!(arr[ Range::from(1..3 )], [ 1, 2 ]);
15//! assert_eq!(arr[ RangeInclusive::from(1..=3)], [ 1, 2, 3 ]);
16//! ```
17
18use crate::fmt;
19use crate::hash::Hash;
20
21mod iter;
22
23#[stable(feature = "new_range_api_legacy", since = "CURRENT_RUSTC_VERSION")]
24pub mod legacy;
25
26use core::ops::Bound::{self, Excluded, Included, Unbounded};
27
28#[doc(inline)]
29#[stable(feature = "new_range_from_api", since = "1.96.0")]
30pub use iter::RangeFromIter;
31#[doc(inline)]
32#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
33pub use iter::RangeInclusiveIter;
34#[doc(inline)]
35#[stable(feature = "new_range_api", since = "1.96.0")]
36pub use iter::RangeIter;
37
38use crate::iter::Step;
39// FIXME(one_sided_range): These types should move into this module.
40// FIXME(range_into_bounds): Ditto. Also consider re-exporting `RangeBounds` and related.
41use crate::ops::{IntoBounds, OneSidedRange, OneSidedRangeBound, RangeBounds};
42#[doc(inline)]
43#[stable(feature = "new_range_api_exports", since = "CURRENT_RUSTC_VERSION")]
44pub use crate::ops::{RangeFull, RangeTo};
45
46/// A (half-open) range bounded inclusively below and exclusively above.
47///
48/// The `Range` contains all values with `start <= x < end`.
49/// It is empty if `start >= end`.
50///
51/// # Examples
52///
53/// ```
54/// use core::range::Range;
55///
56/// assert_eq!(Range::from(3..5), Range { start: 3, end: 5 });
57/// assert_eq!(3 + 4 + 5, Range::from(3..6).into_iter().sum());
58/// ```
59///
60/// # Edition notes
61///
62/// It is planned that the syntax `start..end` will construct this
63/// type in a future edition, but it does not do so today.
64#[lang = "RangeCopy"]
65#[derive(Copy, Hash)]
66#[derive_const(Clone, Default, PartialEq, Eq)]
67#[stable(feature = "new_range_api", since = "1.96.0")]
68pub struct Range<Idx> {
69 /// The lower bound of the range (inclusive).
70 #[stable(feature = "new_range_api", since = "1.96.0")]
71 pub start: Idx,
72 /// The upper bound of the range (exclusive).
73 #[stable(feature = "new_range_api", since = "1.96.0")]
74 pub end: Idx,
75}
76
77#[stable(feature = "new_range_api", since = "1.96.0")]
78impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
79 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
80 self.start.fmt(fmt)?;
81 write!(fmt, "..")?;
82 self.end.fmt(fmt)?;
83 Ok(())
84 }
85}
86
87impl<Idx: Step> Range<Idx> {
88 /// Creates an iterator over the elements within this range.
89 ///
90 /// Shorthand for `.clone().into_iter()`
91 ///
92 /// # Examples
93 ///
94 /// ```
95 /// use core::range::Range;
96 ///
97 /// let mut i = Range::from(3..9).iter().map(|n| n*n);
98 /// assert_eq!(i.next(), Some(9));
99 /// assert_eq!(i.next(), Some(16));
100 /// assert_eq!(i.next(), Some(25));
101 /// ```
102 #[stable(feature = "new_range_api", since = "1.96.0")]
103 #[inline]
104 pub fn iter(&self) -> RangeIter<Idx> {
105 self.clone().into_iter()
106 }
107}
108
109impl<Idx: PartialOrd<Idx>> Range<Idx> {
110 /// Returns `true` if `item` is contained in the range.
111 ///
112 /// # Examples
113 ///
114 /// ```
115 /// use core::range::Range;
116 ///
117 /// assert!(!Range::from(3..5).contains(&2));
118 /// assert!( Range::from(3..5).contains(&3));
119 /// assert!( Range::from(3..5).contains(&4));
120 /// assert!(!Range::from(3..5).contains(&5));
121 ///
122 /// assert!(!Range::from(3..3).contains(&3));
123 /// assert!(!Range::from(3..2).contains(&3));
124 ///
125 /// assert!( Range::from(0.0..1.0).contains(&0.5));
126 /// assert!(!Range::from(0.0..1.0).contains(&f32::NAN));
127 /// assert!(!Range::from(0.0..f32::NAN).contains(&0.5));
128 /// assert!(!Range::from(f32::NAN..1.0).contains(&0.5));
129 /// ```
130 #[inline]
131 #[stable(feature = "new_range_api", since = "1.96.0")]
132 #[rustc_const_unstable(feature = "const_range", issue = "none")]
133 pub const fn contains<U>(&self, item: &U) -> bool
134 where
135 Idx: [const] PartialOrd<U>,
136 U: ?Sized + [const] PartialOrd<Idx>,
137 {
138 <Self as RangeBounds<Idx>>::contains(self, item)
139 }
140
141 /// Returns `true` if the range contains no items.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use core::range::Range;
147 ///
148 /// assert!(!Range::from(3..5).is_empty());
149 /// assert!( Range::from(3..3).is_empty());
150 /// assert!( Range::from(3..2).is_empty());
151 /// ```
152 ///
153 /// The range is empty if either side is incomparable:
154 ///
155 /// ```
156 /// use core::range::Range;
157 ///
158 /// assert!(!Range::from(3.0..5.0).is_empty());
159 /// assert!( Range::from(3.0..f32::NAN).is_empty());
160 /// assert!( Range::from(f32::NAN..5.0).is_empty());
161 /// ```
162 #[inline]
163 #[stable(feature = "new_range_api", since = "1.96.0")]
164 #[rustc_const_unstable(feature = "const_range", issue = "none")]
165 pub const fn is_empty(&self) -> bool
166 where
167 Idx: [const] PartialOrd,
168 {
169 !(self.start < self.end)
170 }
171}
172
173#[stable(feature = "new_range_api", since = "1.96.0")]
174#[rustc_const_unstable(feature = "const_range", issue = "none")]
175const impl<T> RangeBounds<T> for Range<T> {
176 fn start_bound(&self) -> Bound<&T> {
177 Included(&self.start)
178 }
179 fn end_bound(&self) -> Bound<&T> {
180 Excluded(&self.end)
181 }
182}
183
184// This impl intentionally does not have `T: ?Sized`;
185// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
186//
187/// If you need to use this implementation where `T` is unsized,
188/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
189/// i.e. replace `start..end` with `(Bound::Included(start), Bound::Excluded(end))`.
190#[stable(feature = "new_range_api", since = "1.96.0")]
191#[rustc_const_unstable(feature = "const_range", issue = "none")]
192const impl<T> RangeBounds<T> for Range<&T> {
193 fn start_bound(&self) -> Bound<&T> {
194 Included(self.start)
195 }
196 fn end_bound(&self) -> Bound<&T> {
197 Excluded(self.end)
198 }
199}
200
201#[unstable(feature = "range_into_bounds", issue = "136903")]
202#[rustc_const_unstable(feature = "const_range", issue = "none")]
203const impl<T> IntoBounds<T> for Range<T> {
204 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
205 (Included(self.start), Excluded(self.end))
206 }
207}
208
209#[stable(feature = "new_range_api", since = "1.96.0")]
210#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
211const impl<T> From<Range<T>> for legacy::Range<T> {
212 #[inline]
213 fn from(value: Range<T>) -> Self {
214 Self { start: value.start, end: value.end }
215 }
216}
217#[stable(feature = "new_range_api", since = "1.96.0")]
218#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
219const impl<T> From<legacy::Range<T>> for Range<T> {
220 #[inline]
221 fn from(value: legacy::Range<T>) -> Self {
222 Self { start: value.start, end: value.end }
223 }
224}
225
226/// A range bounded inclusively below and above.
227///
228/// The `RangeInclusive` contains all values with `x >= start`
229/// and `x <= last`. It is empty unless `start <= last`.
230///
231/// # Examples
232///
233/// ```
234/// use core::range::RangeInclusive;
235///
236/// assert_eq!(RangeInclusive::from(3..=5), RangeInclusive { start: 3, last: 5 });
237/// assert_eq!(3 + 4 + 5, RangeInclusive::from(3..=5).into_iter().sum());
238/// ```
239///
240/// # Edition notes
241///
242/// It is planned that the syntax `start..=last` will construct this
243/// type in a future edition, but it does not do so today.
244#[lang = "RangeInclusiveCopy"]
245#[derive(Clone, Copy, PartialEq, Eq, Hash)]
246#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
247pub struct RangeInclusive<Idx> {
248 /// The lower bound of the range (inclusive).
249 #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
250 pub start: Idx,
251 /// The upper bound of the range (inclusive).
252 #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
253 pub last: Idx,
254}
255
256#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
257impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
258 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
259 self.start.fmt(fmt)?;
260 write!(fmt, "..=")?;
261 self.last.fmt(fmt)?;
262 Ok(())
263 }
264}
265
266impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
267 /// Returns `true` if `item` is contained in the range.
268 ///
269 /// # Examples
270 ///
271 /// ```
272 /// use core::range::RangeInclusive;
273 ///
274 /// assert!(!RangeInclusive::from(3..=5).contains(&2));
275 /// assert!( RangeInclusive::from(3..=5).contains(&3));
276 /// assert!( RangeInclusive::from(3..=5).contains(&4));
277 /// assert!( RangeInclusive::from(3..=5).contains(&5));
278 /// assert!(!RangeInclusive::from(3..=5).contains(&6));
279 ///
280 /// assert!( RangeInclusive::from(3..=3).contains(&3));
281 /// assert!(!RangeInclusive::from(3..=2).contains(&3));
282 ///
283 /// assert!( RangeInclusive::from(0.0..=1.0).contains(&1.0));
284 /// assert!(!RangeInclusive::from(0.0..=1.0).contains(&f32::NAN));
285 /// assert!(!RangeInclusive::from(0.0..=f32::NAN).contains(&0.0));
286 /// assert!(!RangeInclusive::from(f32::NAN..=1.0).contains(&1.0));
287 /// ```
288 #[inline]
289 #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
290 #[rustc_const_unstable(feature = "const_range", issue = "none")]
291 pub const fn contains<U>(&self, item: &U) -> bool
292 where
293 Idx: [const] PartialOrd<U>,
294 U: ?Sized + [const] PartialOrd<Idx>,
295 {
296 <Self as RangeBounds<Idx>>::contains(self, item)
297 }
298
299 /// Returns `true` if the range contains no items.
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// use core::range::RangeInclusive;
305 ///
306 /// assert!(!RangeInclusive::from(3..=5).is_empty());
307 /// assert!(!RangeInclusive::from(3..=3).is_empty());
308 /// assert!( RangeInclusive::from(3..=2).is_empty());
309 /// ```
310 ///
311 /// The range is empty if either side is incomparable:
312 ///
313 /// ```
314 /// use core::range::RangeInclusive;
315 ///
316 /// assert!(!RangeInclusive::from(3.0..=5.0).is_empty());
317 /// assert!( RangeInclusive::from(3.0..=f32::NAN).is_empty());
318 /// assert!( RangeInclusive::from(f32::NAN..=5.0).is_empty());
319 /// ```
320 #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
321 #[inline]
322 #[rustc_const_unstable(feature = "const_range", issue = "none")]
323 pub const fn is_empty(&self) -> bool
324 where
325 Idx: [const] PartialOrd,
326 {
327 !(self.start <= self.last)
328 }
329}
330
331impl<Idx: Step> RangeInclusive<Idx> {
332 /// Creates an iterator over the elements within this range.
333 ///
334 /// Shorthand for `.clone().into_iter()`
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// use core::range::RangeInclusive;
340 ///
341 /// let mut i = RangeInclusive::from(3..=8).iter().map(|n| n*n);
342 /// assert_eq!(i.next(), Some(9));
343 /// assert_eq!(i.next(), Some(16));
344 /// assert_eq!(i.next(), Some(25));
345 /// ```
346 #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
347 #[inline]
348 pub fn iter(&self) -> RangeInclusiveIter<Idx> {
349 self.clone().into_iter()
350 }
351}
352
353#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
354#[rustc_const_unstable(feature = "const_range", issue = "none")]
355const impl<T> RangeBounds<T> for RangeInclusive<T> {
356 fn start_bound(&self) -> Bound<&T> {
357 Included(&self.start)
358 }
359 fn end_bound(&self) -> Bound<&T> {
360 Included(&self.last)
361 }
362}
363
364// This impl intentionally does not have `T: ?Sized`;
365// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
366//
367/// If you need to use this implementation where `T` is unsized,
368/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
369/// i.e. replace `start..=end` with `(Bound::Included(start), Bound::Included(end))`.
370#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
371#[rustc_const_unstable(feature = "const_range", issue = "none")]
372const impl<T> RangeBounds<T> for RangeInclusive<&T> {
373 fn start_bound(&self) -> Bound<&T> {
374 Included(self.start)
375 }
376 fn end_bound(&self) -> Bound<&T> {
377 Included(self.last)
378 }
379}
380
381// #[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
382#[unstable(feature = "range_into_bounds", issue = "136903")]
383#[rustc_const_unstable(feature = "const_range", issue = "none")]
384const impl<T> IntoBounds<T> for RangeInclusive<T> {
385 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
386 (Included(self.start), Included(self.last))
387 }
388}
389
390#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
391#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
392const impl<T> From<RangeInclusive<T>> for legacy::RangeInclusive<T> {
393 #[inline]
394 fn from(value: RangeInclusive<T>) -> Self {
395 Self::new(value.start, value.last)
396 }
397}
398#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
399#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
400const impl<T> From<legacy::RangeInclusive<T>> for RangeInclusive<T> {
401 /// Converts from a legacy range to a non-legacy range, potentially panicking.
402 ///
403 /// # Panics
404 ///
405 /// If the legacy range iterator has been exhausted,
406 /// this function will either panic or return an empty range.
407 ///
408 /// # Examples
409 ///
410 /// ```
411 /// use core::range::legacy;
412 /// use core::range::RangeInclusive;
413 ///
414 /// let single: legacy::RangeInclusive<i32> = 0..=1;
415 /// let single = RangeInclusive::from(single);
416 /// assert_eq!((single.start, single.last), (0, 1));
417 ///
418 /// let empty: legacy::RangeInclusive<i32> = 0..=0;
419 /// let empty = RangeInclusive::from(empty);
420 /// assert_eq!((empty.start, empty.last), (0, 0));
421 /// ```
422 ///
423 /// ```
424 /// # // This test requires unwinding to work.
425 /// # // Disable it when unwinding isn't available.
426 /// # #[cfg(panic = "unwind")]
427 /// # fn main() {
428 /// use core::range::legacy;
429 /// use core::range::RangeInclusive;
430 /// use std::panic::catch_unwind;
431 ///
432 /// let mut exhausted: legacy::RangeInclusive<i32> = 0..=0;
433 /// exhausted.next();
434 /// let result = catch_unwind(|| RangeInclusive::from(exhausted));
435 /// // The `from` call either panicked or returned an empty range.
436 /// assert!(result.is_err() || result.is_ok_and(|range| range.is_empty()));
437 /// # }
438 /// # #[cfg(not(panic = "unwind"))]
439 /// # fn main() {}
440 /// ```
441 #[inline]
442 fn from(value: legacy::RangeInclusive<T>) -> Self {
443 assert!(
444 !value.exhausted,
445 "attempted to convert from an exhausted `legacy::RangeInclusive`"
446 );
447
448 let (start, last) = value.into_inner();
449 RangeInclusive { start, last }
450 }
451}
452
453/// A range only bounded inclusively below.
454///
455/// The `RangeFrom` contains all values with `x >= start`.
456///
457/// *Note*: Overflow in the [`IntoIterator`] implementation (when the contained
458/// data type reaches its numerical limit) is allowed to panic, wrap, or
459/// saturate. This behavior is defined by the implementation of the [`Step`]
460/// trait. For primitive integers, this follows the normal rules, and respects
461/// the overflow checks profile (panic in debug, wrap in release). Unlike
462/// its legacy counterpart, the iterator will only panic after yielding the
463/// maximum value when overflow checks are enabled.
464///
465/// [`Step`]: crate::iter::Step
466///
467/// # Examples
468///
469/// ```
470/// use core::range::RangeFrom;
471///
472/// assert_eq!(RangeFrom::from(2..), core::range::RangeFrom { start: 2 });
473/// assert_eq!(2 + 3 + 4, RangeFrom::from(2..).into_iter().take(3).sum());
474/// ```
475///
476/// # Edition notes
477///
478/// It is planned that the syntax `start..` will construct this
479/// type in a future edition, but it does not do so today.
480#[lang = "RangeFromCopy"]
481#[derive(Copy, Hash)]
482#[derive_const(Clone, PartialEq, Eq)]
483#[stable(feature = "new_range_from_api", since = "1.96.0")]
484pub struct RangeFrom<Idx> {
485 /// The lower bound of the range (inclusive).
486 #[stable(feature = "new_range_from_api", since = "1.96.0")]
487 pub start: Idx,
488}
489
490#[stable(feature = "new_range_from_api", since = "1.96.0")]
491impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
492 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
493 self.start.fmt(fmt)?;
494 write!(fmt, "..")?;
495 Ok(())
496 }
497}
498
499impl<Idx: Step> RangeFrom<Idx> {
500 /// Creates an iterator over the elements within this range.
501 ///
502 /// Shorthand for `.clone().into_iter()`
503 ///
504 /// # Examples
505 ///
506 /// ```
507 /// use core::range::RangeFrom;
508 ///
509 /// let mut i = RangeFrom::from(3..).iter().map(|n| n*n);
510 /// assert_eq!(i.next(), Some(9));
511 /// assert_eq!(i.next(), Some(16));
512 /// assert_eq!(i.next(), Some(25));
513 /// ```
514 #[stable(feature = "new_range_from_api", since = "1.96.0")]
515 #[inline]
516 pub fn iter(&self) -> RangeFromIter<Idx> {
517 self.clone().into_iter()
518 }
519}
520
521impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
522 /// Returns `true` if `item` is contained in the range.
523 ///
524 /// # Examples
525 ///
526 /// ```
527 /// use core::range::RangeFrom;
528 ///
529 /// assert!(!RangeFrom::from(3..).contains(&2));
530 /// assert!( RangeFrom::from(3..).contains(&3));
531 /// assert!( RangeFrom::from(3..).contains(&1_000_000_000));
532 ///
533 /// assert!( RangeFrom::from(0.0..).contains(&0.5));
534 /// assert!(!RangeFrom::from(0.0..).contains(&f32::NAN));
535 /// assert!(!RangeFrom::from(f32::NAN..).contains(&0.5));
536 /// ```
537 #[inline]
538 #[stable(feature = "new_range_from_api", since = "1.96.0")]
539 #[rustc_const_unstable(feature = "const_range", issue = "none")]
540 pub const fn contains<U>(&self, item: &U) -> bool
541 where
542 Idx: [const] PartialOrd<U>,
543 U: ?Sized + [const] PartialOrd<Idx>,
544 {
545 <Self as RangeBounds<Idx>>::contains(self, item)
546 }
547}
548
549#[stable(feature = "new_range_from_api", since = "1.96.0")]
550#[rustc_const_unstable(feature = "const_range", issue = "none")]
551const impl<T> RangeBounds<T> for RangeFrom<T> {
552 fn start_bound(&self) -> Bound<&T> {
553 Included(&self.start)
554 }
555 fn end_bound(&self) -> Bound<&T> {
556 Unbounded
557 }
558}
559
560// This impl intentionally does not have `T: ?Sized`;
561// see https://github.com/rust-lang/rust/pull/61584 for discussion of why.
562//
563/// If you need to use this implementation where `T` is unsized,
564/// consider using the `RangeBounds` impl for a 2-tuple of [`Bound<&T>`][Bound],
565/// i.e. replace `start..` with `(Bound::Included(start), Bound::Unbounded)`.
566#[stable(feature = "new_range_from_api", since = "1.96.0")]
567#[rustc_const_unstable(feature = "const_range", issue = "none")]
568const impl<T> RangeBounds<T> for RangeFrom<&T> {
569 fn start_bound(&self) -> Bound<&T> {
570 Included(self.start)
571 }
572 fn end_bound(&self) -> Bound<&T> {
573 Unbounded
574 }
575}
576
577#[unstable(feature = "range_into_bounds", issue = "136903")]
578#[rustc_const_unstable(feature = "const_range", issue = "none")]
579const impl<T> IntoBounds<T> for RangeFrom<T> {
580 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
581 (Included(self.start), Unbounded)
582 }
583}
584
585#[unstable(feature = "one_sided_range", issue = "69780")]
586#[rustc_const_unstable(feature = "const_range", issue = "none")]
587const impl<T> OneSidedRange<T> for RangeFrom<T>
588where
589 Self: RangeBounds<T>,
590{
591 fn bound(self) -> (OneSidedRangeBound, T) {
592 (OneSidedRangeBound::StartInclusive, self.start)
593 }
594}
595
596#[stable(feature = "new_range_from_api", since = "1.96.0")]
597#[rustc_const_unstable(feature = "const_index", issue = "143775")]
598const impl<T> From<RangeFrom<T>> for legacy::RangeFrom<T> {
599 #[inline]
600 fn from(value: RangeFrom<T>) -> Self {
601 Self { start: value.start }
602 }
603}
604#[stable(feature = "new_range_from_api", since = "1.96.0")]
605#[rustc_const_unstable(feature = "const_index", issue = "143775")]
606const impl<T> From<legacy::RangeFrom<T>> for RangeFrom<T> {
607 #[inline]
608 fn from(value: legacy::RangeFrom<T>) -> Self {
609 Self { start: value.start }
610 }
611}
612
613/// A range only bounded inclusively above.
614///
615/// The `RangeToInclusive` contains all values with `x <= last`.
616/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
617///
618/// # Examples
619///
620/// ```standalone_crate
621/// #![feature(new_range)]
622/// assert_eq!((..=5), std::range::RangeToInclusive { last: 5 });
623/// ```
624///
625/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
626/// `for` loop directly. This won't compile:
627///
628/// ```compile_fail,E0277
629/// // error[E0277]: the trait bound `std::range::RangeToInclusive<{integer}>:
630/// // std::iter::Iterator` is not satisfied
631/// for i in ..=5 {
632/// // ...
633/// }
634/// ```
635///
636/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
637/// array elements up to and including the index indicated by `last`.
638///
639/// ```
640/// let arr = [0, 1, 2, 3, 4];
641/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
642/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
643/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); // This is a `RangeToInclusive`
644/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
645/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
646/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
647/// ```
648///
649/// [slicing index]: crate::slice::SliceIndex
650///
651/// # Edition notes
652///
653/// It is planned that the syntax `..=last` will construct this
654/// type in a future edition, but it does not do so today.
655#[lang = "RangeToInclusiveCopy"]
656#[doc(alias = "..=")]
657#[derive(Copy, Clone, PartialEq, Eq, Hash)]
658#[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
659pub struct RangeToInclusive<Idx> {
660 /// The upper bound of the range (inclusive)
661 #[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
662 pub last: Idx,
663}
664
665#[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
666impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
667 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
668 write!(fmt, "..=")?;
669 self.last.fmt(fmt)?;
670 Ok(())
671 }
672}
673
674impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
675 /// Returns `true` if `item` is contained in the range.
676 ///
677 /// # Examples
678 ///
679 /// ```
680 /// assert!( (..=5).contains(&-1_000_000_000));
681 /// assert!( (..=5).contains(&5));
682 /// assert!(!(..=5).contains(&6));
683 ///
684 /// assert!( (..=1.0).contains(&1.0));
685 /// assert!(!(..=1.0).contains(&f32::NAN));
686 /// assert!(!(..=f32::NAN).contains(&0.5));
687 /// ```
688 #[inline]
689 #[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
690 #[rustc_const_unstable(feature = "const_range", issue = "none")]
691 pub const fn contains<U>(&self, item: &U) -> bool
692 where
693 Idx: [const] PartialOrd<U>,
694 U: ?Sized + [const] PartialOrd<Idx>,
695 {
696 <Self as RangeBounds<Idx>>::contains(self, item)
697 }
698}
699
700#[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
701impl<T> From<legacy::RangeToInclusive<T>> for RangeToInclusive<T> {
702 fn from(value: legacy::RangeToInclusive<T>) -> Self {
703 Self { last: value.end }
704 }
705}
706#[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
707impl<T> From<RangeToInclusive<T>> for legacy::RangeToInclusive<T> {
708 fn from(value: RangeToInclusive<T>) -> Self {
709 Self { end: value.last }
710 }
711}
712
713// RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
714// because underflow would be possible with (..0).into()
715
716#[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
717#[rustc_const_unstable(feature = "const_range", issue = "none")]
718const impl<T> RangeBounds<T> for RangeToInclusive<T> {
719 fn start_bound(&self) -> Bound<&T> {
720 Unbounded
721 }
722 fn end_bound(&self) -> Bound<&T> {
723 Included(&self.last)
724 }
725}
726
727#[stable(feature = "new_range_to_inclusive_api", since = "1.96.0")]
728#[rustc_const_unstable(feature = "const_range", issue = "none")]
729const impl<T> RangeBounds<T> for RangeToInclusive<&T> {
730 fn start_bound(&self) -> Bound<&T> {
731 Unbounded
732 }
733 fn end_bound(&self) -> Bound<&T> {
734 Included(self.last)
735 }
736}
737
738#[unstable(feature = "range_into_bounds", issue = "136903")]
739#[rustc_const_unstable(feature = "const_range", issue = "none")]
740const impl<T> IntoBounds<T> for RangeToInclusive<T> {
741 fn into_bounds(self) -> (Bound<T>, Bound<T>) {
742 (Unbounded, Included(self.last))
743 }
744}
745
746#[unstable(feature = "one_sided_range", issue = "69780")]
747#[rustc_const_unstable(feature = "const_range", issue = "none")]
748const impl<T> OneSidedRange<T> for RangeToInclusive<T>
749where
750 Self: RangeBounds<T>,
751{
752 fn bound(self) -> (OneSidedRangeBound, T) {
753 (OneSidedRangeBound::EndInclusive, self.last)
754 }
755}