Skip to content

inclusive Ranges: change end to last #144765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ language_item_table! {
RangeFromCopy, sym::RangeFromCopy, range_from_copy_struct, Target::Struct, GenericRequirement::None;
RangeCopy, sym::RangeCopy, range_copy_struct, Target::Struct, GenericRequirement::None;
RangeInclusiveCopy, sym::RangeInclusiveCopy, range_inclusive_copy_struct, Target::Struct, GenericRequirement::None;
RangeToInclusiveCopy, sym::RangeToInclusiveCopy, range_to_inclusive_copy_struct, Target::Struct, GenericRequirement::None;

String, sym::String, string, Target::Struct, GenericRequirement::None;
CStr, sym::CStr, c_str, Target::Struct, GenericRequirement::None;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ symbols! {
RangeSub,
RangeTo,
RangeToInclusive,
RangeToInclusiveCopy,
Rc,
RcWeak,
Ready,
Expand Down
138 changes: 119 additions & 19 deletions library/core/src/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive};
#[doc(inline)]
pub use crate::iter::Step;
#[doc(inline)]
pub use crate::ops::{
Bound, IntoBounds, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive,
};
pub use crate::ops::{Bound, IntoBounds, OneSidedRange, RangeBounds, RangeFull, RangeTo};

/// A (half-open) range bounded inclusively below and exclusively above
/// (`start..end` in a future edition).
Expand Down Expand Up @@ -203,20 +201,20 @@ impl<T> const From<legacy::Range<T>> for Range<T> {
}
}

/// A range bounded inclusively below and above (`start..=end`).
/// A range bounded inclusively below and above (`start..=last`).
///
/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
/// and `x <= end`. It is empty unless `start <= end`.
/// The `RangeInclusive` `start..=last` contains all values with `x >= start`
/// and `x <= last`. It is empty unless `start <= last`.
///
/// # Examples
///
/// The `start..=end` syntax is a `RangeInclusive`:
/// The `start..=last` syntax is a `RangeInclusive`:
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeInclusive;
///
/// assert_eq!(RangeInclusive::from(3..=5), RangeInclusive { start: 3, end: 5 });
/// assert_eq!(RangeInclusive::from(3..=5), RangeInclusive { start: 3, last: 5 });
/// assert_eq!(3 + 4 + 5, RangeInclusive::from(3..=5).into_iter().sum());
/// ```
#[lang = "RangeInclusiveCopy"]
Expand All @@ -228,15 +226,15 @@ pub struct RangeInclusive<Idx> {
pub start: Idx,
/// The upper bound of the range (inclusive).
#[unstable(feature = "new_range_api", issue = "125687")]
pub end: Idx,
pub last: Idx,
}

#[unstable(feature = "new_range_api", issue = "125687")]
impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.start.fmt(fmt)?;
write!(fmt, "..=")?;
self.end.fmt(fmt)?;
self.last.fmt(fmt)?;
Ok(())
}
}
Expand Down Expand Up @@ -300,7 +298,7 @@ impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
#[unstable(feature = "new_range_api", issue = "125687")]
#[inline]
pub fn is_empty(&self) -> bool {
!(self.start <= self.end)
!(self.start <= self.last)
}
}

Expand Down Expand Up @@ -329,10 +327,10 @@ impl<Idx: Step> RangeInclusive<Idx> {

impl RangeInclusive<usize> {
/// Converts to an exclusive `Range` for `SliceIndex` implementations.
/// The caller is responsible for dealing with `end == usize::MAX`.
/// The caller is responsible for dealing with `last == usize::MAX`.
#[inline]
pub(crate) const fn into_slice_range(self) -> Range<usize> {
Range { start: self.start, end: self.end + 1 }
Range { start: self.start, end: self.last + 1 }
}
}

Expand All @@ -342,7 +340,7 @@ impl<T> RangeBounds<T> for RangeInclusive<T> {
Included(&self.start)
}
fn end_bound(&self) -> Bound<&T> {
Included(&self.end)
Included(&self.last)
}
}

Expand All @@ -352,15 +350,15 @@ impl<T> RangeBounds<T> for RangeInclusive<&T> {
Included(self.start)
}
fn end_bound(&self) -> Bound<&T> {
Included(self.end)
Included(self.last)
}
}

// #[unstable(feature = "range_into_bounds", issue = "136903")]
#[unstable(feature = "new_range_api", issue = "125687")]
impl<T> IntoBounds<T> for RangeInclusive<T> {
fn into_bounds(self) -> (Bound<T>, Bound<T>) {
(Included(self.start), Included(self.end))
(Included(self.start), Included(self.last))
}
}

Expand All @@ -369,7 +367,7 @@ impl<T> IntoBounds<T> for RangeInclusive<T> {
impl<T> const From<RangeInclusive<T>> for legacy::RangeInclusive<T> {
#[inline]
fn from(value: RangeInclusive<T>) -> Self {
Self::new(value.start, value.end)
Self::new(value.start, value.last)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
Expand All @@ -381,8 +379,8 @@ impl<T> From<legacy::RangeInclusive<T>> for RangeInclusive<T> {
"attempted to convert from an exhausted `legacy::RangeInclusive` (unspecified behavior)"
);

let (start, end) = value.into_inner();
RangeInclusive { start, end }
let (start, last) = value.into_inner();
RangeInclusive { start, last }
}
}

Expand Down Expand Up @@ -525,3 +523,105 @@ impl<T> const From<legacy::RangeFrom<T>> for RangeFrom<T> {
Self { start: value.start }
}
}

/// A range only bounded inclusively above (`..=last`).
///
/// The `RangeToInclusive` `..=last` contains all values with `x <= last`.
/// It cannot serve as an [`Iterator`] because it doesn't have a starting point.
///
/// # Examples
///
/// The `..=last` syntax is a `RangeToInclusive`:
///
/// ```
/// assert_eq!((..=5), std::ops::RangeToInclusive{ last: 5 });
/// ```
///
/// It does not have an [`IntoIterator`] implementation, so you can't use it in a
/// `for` loop directly. This won't compile:
///
/// ```compile_fail,E0277
/// // error[E0277]: the trait bound `std::ops::RangeToInclusive<{integer}>:
/// // std::iter::Iterator` is not satisfied
/// for i in ..=5 {
/// // ...
/// }
/// ```
///
/// When used as a [slicing index], `RangeToInclusive` produces a slice of all
/// array elements up to and including the index indicated by `last`.
///
/// ```
/// let arr = [0, 1, 2, 3, 4];
/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]);
/// assert_eq!(arr[ .. 3], [0, 1, 2 ]);
/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); // This is a `RangeToInclusive`
/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]);
/// assert_eq!(arr[1.. 3], [ 1, 2 ]);
/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]);
/// ```
///
/// [slicing index]: crate::slice::SliceIndex
#[lang = "RangeToInclusiveCopy"]
#[doc(alias = "..=")]
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[unstable(feature = "new_range_api", issue = "125687")]
pub struct RangeToInclusive<Idx> {
/// The upper bound of the range (inclusive)
#[unstable(feature = "new_range_api", issue = "125687")]
pub last: Idx,
}

#[unstable(feature = "new_range_api", issue = "125687")]
impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "..=")?;
self.last.fmt(fmt)?;
Ok(())
}
}

impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// assert!( (..=5).contains(&-1_000_000_000));
/// assert!( (..=5).contains(&5));
/// assert!(!(..=5).contains(&6));
///
/// assert!( (..=1.0).contains(&1.0));
/// assert!(!(..=1.0).contains(&f32::NAN));
/// assert!(!(..=f32::NAN).contains(&0.5));
/// ```
#[inline]
#[unstable(feature = "new_range_api", issue = "125687")]
pub fn contains<U>(&self, item: &U) -> bool
where
Idx: PartialOrd<U>,
U: ?Sized + PartialOrd<Idx>,
{
<Self as RangeBounds<Idx>>::contains(self, item)
}
}

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

#[unstable(feature = "new_range_api", issue = "125687")]
impl<T> RangeBounds<T> for RangeToInclusive<T> {
fn start_bound(&self) -> Bound<&T> {
Unbounded
}
fn end_bound(&self) -> Bound<&T> {
Included(&self.last)
}
}

#[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.last))
}
}
2 changes: 1 addition & 1 deletion library/core/src/range/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl<A: Step> IterRangeInclusive<A> {
return None;
}

Some(RangeInclusive { start: self.0.start, end: self.0.end })
Some(RangeInclusive { start: self.0.start, last: self.0.end })
}
}

Expand Down
8 changes: 4 additions & 4 deletions library/core/src/str/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,11 +677,11 @@ unsafe impl const SliceIndex<str> for range::RangeInclusive<usize> {
type Output = str;
#[inline]
fn get(self, slice: &str) -> Option<&Self::Output> {
if self.end == usize::MAX { None } else { self.into_slice_range().get(slice) }
if self.last == usize::MAX { None } else { self.into_slice_range().get(slice) }
}
#[inline]
fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
if self.end == usize::MAX { None } else { self.into_slice_range().get_mut(slice) }
if self.last == usize::MAX { None } else { self.into_slice_range().get_mut(slice) }
}
#[inline]
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output {
Expand All @@ -695,14 +695,14 @@ unsafe impl const SliceIndex<str> for range::RangeInclusive<usize> {
}
#[inline]
fn index(self, slice: &str) -> &Self::Output {
if self.end == usize::MAX {
if self.last == usize::MAX {
str_index_overflow_fail();
}
self.into_slice_range().index(slice)
}
#[inline]
fn index_mut(self, slice: &mut str) -> &mut Self::Output {
if self.end == usize::MAX {
if self.last == usize::MAX {
str_index_overflow_fail();
}
self.into_slice_range().index_mut(slice)
Expand Down
Loading