add `new_range_api` for RFC 3550

This includes a `From<legacy::RangeInclusive> for RangeInclusive` impl for convenience, instead of the `TryFrom` impl from the RFC.
Having `From` is highly convenient and the assertion is unlikely to be a problem in practice.

This includes re-exports of all existing `Range` types under `core::range`, plus the range-related traits (`RangeBounds`, `Step`, `OneSidedRange`) and the `Bound` enum.

Currently the iterators are just wrappers around the old range types,
and most other trait impls delegate to the old rage types as well.

Also includes an `.iter()` shorthand for `.clone().into_iter()`
This commit is contained in:
Peter Jaszkowiak 2024-05-19 12:28:26 -06:00
parent 6e2780775f
commit ffea65bf61
8 changed files with 1168 additions and 5 deletions

View File

@ -395,6 +395,8 @@ pub mod panicking;
#[unstable(feature = "core_pattern_types", issue = "none")]
pub mod pat;
pub mod pin;
#[unstable(feature = "new_range_api", issue = "125687")]
pub mod range;
pub mod result;
pub mod sync;

494
library/core/src/range.rs Normal file
View File

@ -0,0 +1,494 @@
//! # Experimental replacement range types
//!
//! The types within this module are meant to replace the existing
//! `Range`, `RangeInclusive`, and `RangeFrom` types in a future edition.
//!
//! ```
//! #![feature(new_range_api)]
//! use core::range::{Range, RangeFrom, RangeInclusive};
//!
//! 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 ]);
//! assert_eq!(arr[ RangeFrom::from(1.. )], [ 1, 2, 3, 4]);
//! assert_eq!(arr[ Range::from(1..3 )], [ 1, 2 ]);
//! assert_eq!(arr[RangeInclusive::from(1..=3)], [ 1, 2, 3 ]);
//! ```
use crate::fmt;
use crate::hash::Hash;
mod iter;
#[unstable(feature = "new_range_api", issue = "125687")]
pub mod legacy;
#[doc(inline)]
pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive};
use Bound::{Excluded, Included, Unbounded};
#[doc(inline)]
pub use crate::iter::Step;
#[doc(inline)]
pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive};
/// A (half-open) range bounded inclusively below and exclusively above
/// (`start..end` in a future edition).
///
/// The range `start..end` contains all values with `start <= x < end`.
/// It is empty if `start >= end`.
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::Range;
///
/// assert_eq!(Range::from(3..5), Range { start: 3, end: 5 });
/// assert_eq!(3 + 4 + 5, Range::from(3..6).into_iter().sum());
/// ```
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
#[unstable(feature = "new_range_api", issue = "125687")]
pub struct Range<Idx> {
/// The lower bound of the range (inclusive).
#[unstable(feature = "new_range_api", issue = "125687")]
pub start: Idx,
/// The upper bound of the range (exclusive).
#[unstable(feature = "new_range_api", issue = "125687")]
pub end: Idx,
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.start.fmt(fmt)?;
write!(fmt, "..")?;
self.end.fmt(fmt)?;
Ok(())
}
}
impl<Idx: Step> Range<Idx> {
/// Create an iterator over the elements within this range.
///
/// Shorthand for `.clone().into_iter()`
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::Range;
///
/// let mut i = Range::from(3..9).iter().map(|n| n*n);
/// assert_eq!(i.next(), Some(9));
/// assert_eq!(i.next(), Some(16));
/// assert_eq!(i.next(), Some(25));
/// ```
#[unstable(feature = "new_range_api", issue = "125687")]
#[inline]
pub fn iter(&self) -> IterRange<Idx> {
self.clone().into_iter()
}
}
impl<Idx: PartialOrd<Idx>> Range<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::Range;
///
/// assert!(!Range::from(3..5).contains(&2));
/// assert!( Range::from(3..5).contains(&3));
/// assert!( Range::from(3..5).contains(&4));
/// assert!(!Range::from(3..5).contains(&5));
///
/// assert!(!Range::from(3..3).contains(&3));
/// assert!(!Range::from(3..2).contains(&3));
///
/// assert!( Range::from(0.0..1.0).contains(&0.5));
/// assert!(!Range::from(0.0..1.0).contains(&f32::NAN));
/// assert!(!Range::from(0.0..f32::NAN).contains(&0.5));
/// assert!(!Range::from(f32::NAN..1.0).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)
}
/// Returns `true` if the range contains no items.
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::Range;
///
/// assert!(!Range::from(3..5).is_empty());
/// assert!( Range::from(3..3).is_empty());
/// assert!( Range::from(3..2).is_empty());
/// ```
///
/// The range is empty if either side is incomparable:
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::Range;
///
/// assert!(!Range::from(3.0..5.0).is_empty());
/// assert!( Range::from(3.0..f32::NAN).is_empty());
/// assert!( Range::from(f32::NAN..5.0).is_empty());
/// ```
#[inline]
#[unstable(feature = "new_range_api", issue = "125687")]
pub fn is_empty(&self) -> bool {
!(self.start < self.end)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
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 = "new_range_api", issue = "125687")]
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 = "new_range_api", issue = "125687")]
impl<T> From<Range<T>> for legacy::Range<T> {
#[inline]
fn from(value: Range<T>) -> Self {
Self { start: value.start, end: value.end }
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<T> From<legacy::Range<T>> for Range<T> {
#[inline]
fn from(value: legacy::Range<T>) -> Self {
Self { start: value.start, end: value.end }
}
}
/// A range bounded inclusively below and above (`start..=end`).
///
/// The `RangeInclusive` `start..=end` contains all values with `x >= start`
/// and `x <= end`. It is empty unless `start <= end`.
///
/// # Examples
///
/// The `start..=end` 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!(3 + 4 + 5, RangeInclusive::from(3..=5).into_iter().sum());
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[unstable(feature = "new_range_api", issue = "125687")]
pub struct RangeInclusive<Idx> {
/// The lower bound of the range (inclusive).
#[unstable(feature = "new_range_api", issue = "125687")]
pub start: Idx,
/// The upper bound of the range (inclusive).
#[unstable(feature = "new_range_api", issue = "125687")]
pub end: 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)?;
Ok(())
}
}
impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeInclusive;
///
/// assert!(!RangeInclusive::from(3..=5).contains(&2));
/// assert!( RangeInclusive::from(3..=5).contains(&3));
/// assert!( RangeInclusive::from(3..=5).contains(&4));
/// assert!( RangeInclusive::from(3..=5).contains(&5));
/// assert!(!RangeInclusive::from(3..=5).contains(&6));
///
/// assert!( RangeInclusive::from(3..=3).contains(&3));
/// assert!(!RangeInclusive::from(3..=2).contains(&3));
///
/// assert!( RangeInclusive::from(0.0..=1.0).contains(&1.0));
/// assert!(!RangeInclusive::from(0.0..=1.0).contains(&f32::NAN));
/// assert!(!RangeInclusive::from(0.0..=f32::NAN).contains(&0.0));
/// assert!(!RangeInclusive::from(f32::NAN..=1.0).contains(&1.0));
/// ```
#[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)
}
/// Returns `true` if the range contains no items.
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeInclusive;
///
/// assert!(!RangeInclusive::from(3..=5).is_empty());
/// assert!(!RangeInclusive::from(3..=3).is_empty());
/// assert!( RangeInclusive::from(3..=2).is_empty());
/// ```
///
/// The range is empty if either side is incomparable:
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeInclusive;
///
/// assert!(!RangeInclusive::from(3.0..=5.0).is_empty());
/// assert!( RangeInclusive::from(3.0..=f32::NAN).is_empty());
/// assert!( RangeInclusive::from(f32::NAN..=5.0).is_empty());
/// ```
#[unstable(feature = "new_range_api", issue = "125687")]
#[inline]
pub fn is_empty(&self) -> bool {
!(self.start <= self.end)
}
}
impl<Idx: Step> RangeInclusive<Idx> {
/// Create an iterator over the elements within this range.
///
/// Shorthand for `.clone().into_iter()`
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeInclusive;
///
/// let mut i = RangeInclusive::from(3..=8).iter().map(|n| n*n);
/// assert_eq!(i.next(), Some(9));
/// assert_eq!(i.next(), Some(16));
/// assert_eq!(i.next(), Some(25));
/// ```
#[unstable(feature = "new_range_api", issue = "125687")]
#[inline]
pub fn iter(&self) -> IterRangeInclusive<Idx> {
self.clone().into_iter()
}
}
impl RangeInclusive<usize> {
/// Converts to an exclusive `Range` for `SliceIndex` implementations.
/// The caller is responsible for dealing with `end == usize::MAX`.
#[inline]
pub(crate) const fn into_slice_range(self) -> Range<usize> {
Range { start: self.start, end: self.end + 1 }
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
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)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
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)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<T> From<RangeInclusive<T>> for legacy::RangeInclusive<T> {
#[inline]
fn from(value: RangeInclusive<T>) -> Self {
Self::new(value.start, value.end)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<T> From<legacy::RangeInclusive<T>> for RangeInclusive<T> {
#[inline]
fn from(value: legacy::RangeInclusive<T>) -> Self {
assert!(
!value.exhausted,
"attempted to convert from an exhausted `legacy::RangeInclusive` (unspecified behavior)"
);
let (start, end) = value.into_inner();
RangeInclusive { start, end }
}
}
/// A range only bounded inclusively below (`start..`).
///
/// The `RangeFrom` `start..` contains all values with `x >= start`.
///
/// *Note*: Overflow in the [`Iterator`] implementation (when the contained
/// data type reaches its numerical limit) is allowed to panic, wrap, or
/// saturate. This behavior is defined by the implementation of the [`Step`]
/// trait. For primitive integers, this follows the normal rules, and respects
/// the overflow checks profile (panic in debug, wrap in release). Note also
/// that overflow happens earlier than you might assume: the overflow happens
/// in the call to `next` that yields the maximum value, as the range must be
/// set to a state to yield the next value.
///
/// [`Step`]: crate::iter::Step
///
/// # Examples
///
/// The `start..` syntax is a `RangeFrom`:
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeFrom;
///
/// assert_eq!(RangeFrom::from(2..), core::range::RangeFrom { start: 2 });
/// assert_eq!(2 + 3 + 4, RangeFrom::from(2..).into_iter().take(3).sum());
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[unstable(feature = "new_range_api", issue = "125687")]
pub struct RangeFrom<Idx> {
/// The lower bound of the range (inclusive).
#[unstable(feature = "new_range_api", issue = "125687")]
pub start: Idx,
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.start.fmt(fmt)?;
write!(fmt, "..")?;
Ok(())
}
}
impl<Idx: Step> RangeFrom<Idx> {
/// Create an iterator over the elements within this range.
///
/// Shorthand for `.clone().into_iter()`
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeFrom;
///
/// let mut i = RangeFrom::from(3..).iter().map(|n| n*n);
/// assert_eq!(i.next(), Some(9));
/// assert_eq!(i.next(), Some(16));
/// assert_eq!(i.next(), Some(25));
/// ```
#[unstable(feature = "new_range_api", issue = "125687")]
#[inline]
pub fn iter(&self) -> IterRangeFrom<Idx> {
self.clone().into_iter()
}
}
impl<Idx: PartialOrd<Idx>> RangeFrom<Idx> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// ```
/// #![feature(new_range_api)]
/// use core::range::RangeFrom;
///
/// assert!(!RangeFrom::from(3..).contains(&2));
/// assert!( RangeFrom::from(3..).contains(&3));
/// assert!( RangeFrom::from(3..).contains(&1_000_000_000));
///
/// assert!( RangeFrom::from(0.0..).contains(&0.5));
/// assert!(!RangeFrom::from(0.0..).contains(&f32::NAN));
/// assert!(!RangeFrom::from(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)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
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 = "new_range_api", issue = "125687")]
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 = "new_range_api", issue = "125687")]
impl<T> From<RangeFrom<T>> for legacy::RangeFrom<T> {
#[inline]
fn from(value: RangeFrom<T>) -> Self {
Self { start: value.start }
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<T> From<legacy::RangeFrom<T>> for RangeFrom<T> {
#[inline]
fn from(value: legacy::RangeFrom<T>) -> Self {
Self { start: value.start }
}
}

View File

@ -0,0 +1,340 @@
use crate::num::NonZero;
use crate::range::{legacy, Range, RangeFrom, RangeInclusive};
use crate::iter::{
FusedIterator, Step, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep,
};
/// By-value [`Range`] iterator.
#[unstable(feature = "new_range_api", issue = "125687")]
#[derive(Debug, Clone)]
pub struct IterRange<A>(legacy::Range<A>);
impl<A> IterRange<A> {
/// Returns the remainder of the range being iterated over.
pub fn remainder(self) -> Range<A> {
Range { start: self.0.start, end: self.0.end }
}
}
/// Safety: This macro must only be used on types that are `Copy` and result in ranges
/// which have an exact `size_hint()` where the upper bound must not be `None`.
macro_rules! unsafe_range_trusted_random_access_impl {
($($t:ty)*) => ($(
#[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")]
unsafe impl TrustedRandomAccess for IterRange<$t> {}
#[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")]
unsafe impl TrustedRandomAccessNoCoerce for IterRange<$t> {
const MAY_HAVE_SIDE_EFFECT: bool = false;
}
)*)
}
unsafe_range_trusted_random_access_impl! {
usize u8 u16
isize i8 i16
}
#[cfg(target_pointer_width = "32")]
unsafe_range_trusted_random_access_impl! {
u32 i32
}
#[cfg(target_pointer_width = "64")]
unsafe_range_trusted_random_access_impl! {
u32 i32
u64 i64
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> Iterator for IterRange<A> {
type Item = A;
#[inline]
fn next(&mut self) -> Option<A> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
#[inline]
fn count(self) -> usize {
self.0.count()
}
#[inline]
fn nth(&mut self, n: usize) -> Option<A> {
self.0.nth(n)
}
#[inline]
fn last(self) -> Option<A> {
self.0.last()
}
#[inline]
fn min(self) -> Option<A>
where
A: Ord,
{
self.0.min()
}
#[inline]
fn max(self) -> Option<A>
where
A: Ord,
{
self.0.max()
}
#[inline]
fn is_sorted(self) -> bool {
true
}
#[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_by(n)
}
#[inline]
unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item
where
Self: TrustedRandomAccessNoCoerce,
{
// SAFETY: The TrustedRandomAccess contract requires that callers only pass an index
// that is in bounds.
// Additionally Self: TrustedRandomAccess is only implemented for Copy types
// which means even repeated reads of the same index would be safe.
unsafe { Step::forward_unchecked(self.0.start.clone(), idx) }
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> DoubleEndedIterator for IterRange<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
self.0.next_back()
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<A> {
self.0.nth_back(n)
}
#[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_back_by(n)
}
}
#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A: TrustedStep> TrustedLen for IterRange<A> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> FusedIterator for IterRange<A> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> IntoIterator for Range<A> {
type Item = A;
type IntoIter = IterRange<A>;
fn into_iter(self) -> Self::IntoIter {
IterRange(self.into())
}
}
/// By-value [`RangeInclusive`] iterator.
#[unstable(feature = "new_range_api", issue = "125687")]
#[derive(Debug, Clone)]
pub struct IterRangeInclusive<A>(legacy::RangeInclusive<A>);
impl<A: Step> IterRangeInclusive<A> {
/// Returns the remainder of the range being iterated over.
///
/// If the iterator is exhausted or empty, returns `None`.
pub fn remainder(self) -> Option<RangeInclusive<A>> {
if self.0.is_empty() {
return None;
}
Some(RangeInclusive { start: self.0.start, end: self.0.end })
}
}
#[unstable(feature = "trusted_random_access", issue = "none")]
impl<A: Step> Iterator for IterRangeInclusive<A> {
type Item = A;
#[inline]
fn next(&mut self) -> Option<A> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
#[inline]
fn count(self) -> usize {
self.0.count()
}
#[inline]
fn nth(&mut self, n: usize) -> Option<A> {
self.0.nth(n)
}
#[inline]
fn last(self) -> Option<A> {
self.0.last()
}
#[inline]
fn min(self) -> Option<A>
where
A: Ord,
{
self.0.min()
}
#[inline]
fn max(self) -> Option<A>
where
A: Ord,
{
self.0.max()
}
#[inline]
fn is_sorted(self) -> bool {
true
}
#[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_by(n)
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> DoubleEndedIterator for IterRangeInclusive<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
self.0.next_back()
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<A> {
self.0.nth_back(n)
}
#[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_back_by(n)
}
}
#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A: TrustedStep> TrustedLen for IterRangeInclusive<A> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> FusedIterator for IterRangeInclusive<A> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> IntoIterator for RangeInclusive<A> {
type Item = A;
type IntoIter = IterRangeInclusive<A>;
fn into_iter(self) -> Self::IntoIter {
IterRangeInclusive(self.into())
}
}
// These macros generate `ExactSizeIterator` impls for various range types.
//
// * `ExactSizeIterator::len` is required to always return an exact `usize`,
// so no range can be longer than `usize::MAX`.
// * For integer types in `Range<_>` this is the case for types narrower than or as wide as `usize`.
// For integer types in `RangeInclusive<_>`
// this is the case for types *strictly narrower* than `usize`
// since e.g. `(0..=u64::MAX).len()` would be `u64::MAX + 1`.
macro_rules! range_exact_iter_impl {
($($t:ty)*) => ($(
#[unstable(feature = "new_range_api", issue = "125687")]
impl ExactSizeIterator for IterRange<$t> { }
)*)
}
macro_rules! range_incl_exact_iter_impl {
($($t:ty)*) => ($(
#[unstable(feature = "new_range_api", issue = "125687")]
impl ExactSizeIterator for IterRangeInclusive<$t> { }
)*)
}
range_exact_iter_impl! {
usize u8 u16
isize i8 i16
}
range_incl_exact_iter_impl! {
u8
i8
}
/// By-value [`RangeFrom`] iterator.
#[unstable(feature = "new_range_api", issue = "125687")]
#[derive(Debug, Clone)]
pub struct IterRangeFrom<A>(legacy::RangeFrom<A>);
impl<A> IterRangeFrom<A> {
/// Returns the remainder of the range being iterated over.
pub fn remainder(self) -> RangeFrom<A> {
RangeFrom { start: self.0.start }
}
}
#[unstable(feature = "trusted_random_access", issue = "none")]
impl<A: Step> Iterator for IterRangeFrom<A> {
type Item = A;
#[inline]
fn next(&mut self) -> Option<A> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
#[inline]
fn nth(&mut self, n: usize) -> Option<A> {
self.0.nth(n)
}
}
#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<A: TrustedStep> TrustedLen for IterRangeFrom<A> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> FusedIterator for IterRangeFrom<A> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl<A: Step> IntoIterator for RangeFrom<A> {
type Item = A;
type IntoIter = IterRangeFrom<A>;
fn into_iter(self) -> Self::IntoIter {
IterRangeFrom(self.into())
}
}

View File

@ -0,0 +1,10 @@
//! # Legacy range types
//!
//! The types within this module will be replaced by the types
//! [`Range`], [`RangeInclusive`], and [`RangeFrom`] in the parent
//! module, [`core::range`].
//!
//! The types here are equivalent to those in [`core::ops`].
#[doc(inline)]
pub use crate::ops::{Range, RangeFrom, RangeInclusive};

View File

@ -2,6 +2,7 @@
use crate::intrinsics::const_eval_select;
use crate::ops;
use crate::range;
use crate::ub_checks::assert_unsafe_precondition;
#[stable(feature = "rust1", since = "1.0.0")]
@ -147,7 +148,8 @@ const unsafe fn get_offset_len_mut_noubcheck<T>(
}
mod private_slice_index {
use super::ops;
use super::{ops, range};
#[stable(feature = "slice_get_slice", since = "1.28.0")]
pub trait Sealed {}
@ -168,6 +170,13 @@ mod private_slice_index {
#[stable(feature = "slice_index_with_ops_bound_pair", since = "1.53.0")]
impl Sealed for (ops::Bound<usize>, ops::Bound<usize>) {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl Sealed for range::Range<usize> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl Sealed for range::RangeInclusive<usize> {}
#[unstable(feature = "new_range_api", issue = "125687")]
impl Sealed for range::RangeFrom<usize> {}
impl Sealed for ops::IndexRange {}
}
@ -473,6 +482,43 @@ unsafe impl<T> SliceIndex<[T]> for ops::Range<usize> {
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
unsafe impl<T> SliceIndex<[T]> for range::Range<usize> {
type Output = [T];
#[inline]
fn get(self, slice: &[T]) -> Option<&[T]> {
ops::Range::from(self).get(slice)
}
#[inline]
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
ops::Range::from(self).get_mut(slice)
}
#[inline]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
// SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
unsafe { ops::Range::from(self).get_unchecked(slice) }
}
#[inline]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
// SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
unsafe { ops::Range::from(self).get_unchecked_mut(slice) }
}
#[inline(always)]
fn index(self, slice: &[T]) -> &[T] {
ops::Range::from(self).index(slice)
}
#[inline]
fn index_mut(self, slice: &mut [T]) -> &mut [T] {
ops::Range::from(self).index_mut(slice)
}
}
/// The methods `index` and `index_mut` panic if the end of the range is out of bounds.
#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
#[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
@ -559,6 +605,43 @@ unsafe impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
unsafe impl<T> SliceIndex<[T]> for range::RangeFrom<usize> {
type Output = [T];
#[inline]
fn get(self, slice: &[T]) -> Option<&[T]> {
ops::RangeFrom::from(self).get(slice)
}
#[inline]
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
ops::RangeFrom::from(self).get_mut(slice)
}
#[inline]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
// SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
unsafe { ops::RangeFrom::from(self).get_unchecked(slice) }
}
#[inline]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
// SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
unsafe { ops::RangeFrom::from(self).get_unchecked_mut(slice) }
}
#[inline]
fn index(self, slice: &[T]) -> &[T] {
ops::RangeFrom::from(self).index(slice)
}
#[inline]
fn index_mut(self, slice: &mut [T]) -> &mut [T] {
ops::RangeFrom::from(self).index_mut(slice)
}
}
#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
#[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
unsafe impl<T> SliceIndex<[T]> for ops::RangeFull {
@ -643,6 +726,43 @@ unsafe impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
unsafe impl<T> SliceIndex<[T]> for range::RangeInclusive<usize> {
type Output = [T];
#[inline]
fn get(self, slice: &[T]) -> Option<&[T]> {
ops::RangeInclusive::from(self).get(slice)
}
#[inline]
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
ops::RangeInclusive::from(self).get_mut(slice)
}
#[inline]
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
// SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
unsafe { ops::RangeInclusive::from(self).get_unchecked(slice) }
}
#[inline]
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
// SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
unsafe { ops::RangeInclusive::from(self).get_unchecked_mut(slice) }
}
#[inline]
fn index(self, slice: &[T]) -> &[T] {
ops::RangeInclusive::from(self).index(slice)
}
#[inline]
fn index_mut(self, slice: &mut [T]) -> &mut [T] {
ops::RangeInclusive::from(self).index_mut(slice)
}
}
/// The methods `index` and `index_mut` panic if the end of the range is out of bounds.
#[stable(feature = "inclusive_range", since = "1.26.0")]
#[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
@ -780,7 +900,7 @@ where
/// Performs bounds-checking of a range without panicking.
///
/// This is a version of [`range`] that returns [`None`] instead of panicking.
/// This is a version of [`range()`] that returns [`None`] instead of panicking.
///
/// # Examples
///

View File

@ -4,6 +4,7 @@ use crate::cmp::Ordering;
use crate::intrinsics::unchecked_sub;
use crate::ops;
use crate::ptr;
use crate::range;
use crate::slice::SliceIndex;
use crate::ub_checks::assert_unsafe_precondition;
@ -261,6 +262,108 @@ unsafe impl SliceIndex<str> for ops::Range<usize> {
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
unsafe impl SliceIndex<str> for range::Range<usize> {
type Output = str;
#[inline]
fn get(self, slice: &str) -> Option<&Self::Output> {
if self.start <= self.end
&& slice.is_char_boundary(self.start)
&& slice.is_char_boundary(self.end)
{
// SAFETY: just checked that `start` and `end` are on a char boundary,
// and we are passing in a safe reference, so the return value will also be one.
// We also checked char boundaries, so this is valid UTF-8.
Some(unsafe { &*self.get_unchecked(slice) })
} else {
None
}
}
#[inline]
fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
if self.start <= self.end
&& slice.is_char_boundary(self.start)
&& slice.is_char_boundary(self.end)
{
// SAFETY: just checked that `start` and `end` are on a char boundary.
// We know the pointer is unique because we got it from `slice`.
Some(unsafe { &mut *self.get_unchecked_mut(slice) })
} else {
None
}
}
#[inline]
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output {
let slice = slice as *const [u8];
assert_unsafe_precondition!(
// We'd like to check that the bounds are on char boundaries,
// but there's not really a way to do so without reading
// behind the pointer, which has aliasing implications.
// It's also not possible to move this check up to
// `str::get_unchecked` without adding a special function
// to `SliceIndex` just for this.
check_library_ub,
"str::get_unchecked requires that the range is within the string slice",
(
start: usize = self.start,
end: usize = self.end,
len: usize = slice.len()
) => end >= start && end <= len,
);
// SAFETY: the caller guarantees that `self` is in bounds of `slice`
// which satisfies all the conditions for `add`.
unsafe {
let new_len = unchecked_sub(self.end, self.start);
ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), new_len) as *const str
}
}
#[inline]
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output {
let slice = slice as *mut [u8];
assert_unsafe_precondition!(
check_library_ub,
"str::get_unchecked_mut requires that the range is within the string slice",
(
start: usize = self.start,
end: usize = self.end,
len: usize = slice.len()
) => end >= start && end <= len,
);
// SAFETY: see comments for `get_unchecked`.
unsafe {
let new_len = unchecked_sub(self.end, self.start);
ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), new_len) as *mut str
}
}
#[inline]
fn index(self, slice: &str) -> &Self::Output {
let (start, end) = (self.start, self.end);
match self.get(slice) {
Some(s) => s,
None => super::slice_error_fail(slice, start, end),
}
}
#[inline]
fn index_mut(self, slice: &mut str) -> &mut Self::Output {
// is_char_boundary checks that the index is in [0, .len()]
// cannot reuse `get` as above, because of NLL trouble
if self.start <= self.end
&& slice.is_char_boundary(self.start)
&& slice.is_char_boundary(self.end)
{
// SAFETY: just checked that `start` and `end` are on a char boundary,
// and we are passing in a safe reference, so the return value will also be one.
unsafe { &mut *self.get_unchecked_mut(slice) }
} else {
super::slice_error_fail(slice, self.start, self.end)
}
}
}
/// Implements substring slicing for arbitrary bounds.
///
/// Returns a slice of the given string bounded by the byte indices
@ -453,6 +556,61 @@ unsafe impl SliceIndex<str> for ops::RangeFrom<usize> {
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
unsafe impl SliceIndex<str> for range::RangeFrom<usize> {
type Output = str;
#[inline]
fn get(self, slice: &str) -> Option<&Self::Output> {
if slice.is_char_boundary(self.start) {
// SAFETY: just checked that `start` is on a char boundary,
// and we are passing in a safe reference, so the return value will also be one.
Some(unsafe { &*self.get_unchecked(slice) })
} else {
None
}
}
#[inline]
fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> {
if slice.is_char_boundary(self.start) {
// SAFETY: just checked that `start` is on a char boundary,
// and we are passing in a safe reference, so the return value will also be one.
Some(unsafe { &mut *self.get_unchecked_mut(slice) })
} else {
None
}
}
#[inline]
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output {
let len = (slice as *const [u8]).len();
// SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
unsafe { (self.start..len).get_unchecked(slice) }
}
#[inline]
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output {
let len = (slice as *mut [u8]).len();
// SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
unsafe { (self.start..len).get_unchecked_mut(slice) }
}
#[inline]
fn index(self, slice: &str) -> &Self::Output {
let (start, end) = (self.start, slice.len());
match self.get(slice) {
Some(s) => s,
None => super::slice_error_fail(slice, start, end),
}
}
#[inline]
fn index_mut(self, slice: &mut str) -> &mut Self::Output {
if slice.is_char_boundary(self.start) {
// SAFETY: just checked that `start` is on a char boundary,
// and we are passing in a safe reference, so the return value will also be one.
unsafe { &mut *self.get_unchecked_mut(slice) }
} else {
super::slice_error_fail(slice, self.start, slice.len())
}
}
}
/// Implements substring slicing with syntax `&self[begin ..= end]` or `&mut
/// self[begin ..= end]`.
///
@ -507,6 +665,43 @@ unsafe impl SliceIndex<str> for ops::RangeInclusive<usize> {
}
}
#[unstable(feature = "new_range_api", issue = "125687")]
unsafe impl 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) }
}
#[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) }
}
#[inline]
unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output {
// SAFETY: the caller must uphold the safety contract for `get_unchecked`.
unsafe { self.into_slice_range().get_unchecked(slice) }
}
#[inline]
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output {
// SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`.
unsafe { self.into_slice_range().get_unchecked_mut(slice) }
}
#[inline]
fn index(self, slice: &str) -> &Self::Output {
if self.end == 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 {
str_index_overflow_fail();
}
self.into_slice_range().index_mut(slice)
}
}
/// Implements substring slicing with syntax `&self[..= end]` or `&mut
/// self[..= end]`.
///

View File

@ -59,6 +59,8 @@ const INTRA_DOC_LINK_EXCEPTIONS: &[(&str, &[&str])] = &[
// This is being used in the sense of 'inclusive range', not a markdown link
("core/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
("std/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
("core/range/legacy/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
("std/range/legacy/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
("core/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
("alloc/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
("std/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),

View File

@ -7,7 +7,7 @@ LL | take_range(0..1);
| arguments to this function are incorrect
|
= note: expected reference `&_`
found struct `Range<{integer}>`
found struct `core::ops::Range<{integer}>`
note: function defined here
--> $DIR/issue-54505-no-std.rs:25:4
|
@ -27,7 +27,7 @@ LL | take_range(1..);
| arguments to this function are incorrect
|
= note: expected reference `&_`
found struct `RangeFrom<{integer}>`
found struct `core::ops::RangeFrom<{integer}>`
note: function defined here
--> $DIR/issue-54505-no-std.rs:25:4
|
@ -67,7 +67,7 @@ LL | take_range(0..=1);
| arguments to this function are incorrect
|
= note: expected reference `&_`
found struct `RangeInclusive<{integer}>`
found struct `core::ops::RangeInclusive<{integer}>`
note: function defined here
--> $DIR/issue-54505-no-std.rs:25:4
|