diff --git a/src/libcore/iter/range.rs b/src/libcore/iter/range.rs index eac3c107d2283..4b0e83767e1f4 100644 --- a/src/libcore/iter/range.rs +++ b/src/libcore/iter/range.rs @@ -5,47 +5,173 @@ use crate::usize; use super::{FusedIterator, TrustedLen}; -/// Objects that can be stepped over in both directions. +/// Objects that have a notion of *successor* and *predecessor*. /// -/// The `steps_between` function provides a way to efficiently compare -/// two `Step` objects. -#[unstable( - feature = "step_trait", - reason = "likely to be replaced by finer-grained traits", - issue = "42168" -)] -pub trait Step: Clone + PartialOrd + Sized { - /// Returns the number of steps between two step objects. The count is - /// inclusive of `start` and exclusive of `end`. - /// - /// Returns `None` if it is not possible to calculate `steps_between` - /// without overflow. +/// The *successor* operation moves towards values that compare greater. +/// The *predecessor* operation moves towards values that compare lesser. +/// +/// # Safety +/// +/// This trait is `unsafe` because its implementation must be correct for +/// the safety of `unsafe trait TrustedLen` implementations, and the results +/// of using this trait can otherwise be trusted by `unsafe` code. +#[unstable(feature = "step_trait", reason = "recently redesigned", issue = "42168")] +pub unsafe trait Step: Clone + PartialOrd + Sized { + /// Returns the number of *successor* steps required to get from `start` to `end`. + /// + /// Returns `None` if the number of steps would overflow `usize` + /// (or is infinite, or if `end` would never be reached). + /// + /// # Invariants + /// + /// For any `a`, `b`, and `n`: + /// + /// * `steps_between(&a, &b) == Some(n)` if and only if `a.forward(n) == Some(b)` + /// * `steps_between(&a, &b) == Some(n)` if and only if `b.backward(n) == Some(a)` + /// * `steps_between(&a, &b) == Some(n)` only if `a <= b` + /// * Corrolary: `steps_between(&a, &b) == Some(0)` if and only if `a == b` + /// * Note that `a <= b` does _not_ imply `steps_between(&a, &b) != None`; + /// this is the case when it would require more than `usize::MAX` steps to get to `b` + /// * `steps_between(&a, &b) == None` if `a > b` fn steps_between(start: &Self, end: &Self) -> Option; - /// Replaces this step with `1`, returning a clone of itself. + /// Returns the value that would be obtained by taking the *successor* + /// of `self` `count` times. + /// + /// Return s`None` if this would overflow the range of values supported by `Self`. + /// + /// # Invariants /// - /// The output of this method should always be greater than the output of replace_zero. - fn replace_one(&mut self) -> Self; + /// For any `a`, `n`, and `m` where `n + m` does not overflow: + /// + /// * `a.forward(n).and_then(|x| x.forward(m)) == a.forward(n + m)` + /// * `a.forward(n)` equals `Step::successor` applied to `a` `n` times + /// * Corollary: `a.forward(0) == Some(a)` + fn forward(&self, count: usize) -> Option; - /// Replaces this step with `0`, returning a clone of itself. + /// Returns the *successor* of `self`. + /// + /// If this would overflow the range of values supported by `Self`, + /// this method is allowed to panic or wrap. Suggested behavior is + /// to panic when debug assertions are enabled, and wrap otherwise. + /// + /// # Invariants + /// + /// For any `a` where `a.successor()` does not overflow: /// - /// The output of this method should always be less than the output of replace_one. - fn replace_zero(&mut self) -> Self; + /// * `a == a.successor().predecessor()` + /// * `a.successor() == a.forward(1).unwrap()` + /// * `a.successor() >= a` + #[inline] + #[unstable(feature = "step_trait_ext", reason = "recently added", issue = "42168")] + fn successor(&self) -> Self { + self.forward(1).expect("overflow in `Step::successor`") + } + + /// Returns the *successor* of `self`. + /// + /// If this would overflow the range of values supported by `Self`, + /// this method is defined to return the input value instead. + /// + /// # Invaraints + /// + /// For any `a` where `a.successor()` does not overflow: + /// + /// * `a.successor_saturating() == a.successor()` + /// + /// For any `a` where `a.successor()` does overflow: + /// + /// * `a.successor_saturating() == a` + #[inline] + #[unstable(feature = "step_trait_ext", reason = "recently added", issue = "42168")] + fn successor_saturating(&self) -> Self { + self.forward(1).unwrap_or_else(|| self.clone()) + } + + /// Returns the *successor* of `self`. + /// + /// # Safety + /// + /// It is undefined behavior if this operation exceeds the range of + /// values supported by `Self`. If you cannot guarantee that this + /// will not overflow, use `forward` or `successor` instead. + /// + /// For any `a`, if there exists `b` such that `b > a`, + /// it is safe to call `a.successor_unchecked()`. + #[inline] + #[unstable(feature = "unchecked_math", reason = "niche optimization path", issue = "none")] + unsafe fn successor_unchecked(&self) -> Self { + self.successor() + } - /// Adds one to this step, returning the result. - fn add_one(&self) -> Self; + /// Returns the value that would be obtained by taking the *predecessor* + /// of `self` `count` times. + /// + /// Returns `None` if this would overflow the range of values supported by `Self`. + /// + /// # Invariants + /// + /// For any `a`, `n`, and `m` where `n + m` does not overflow: + /// + /// * `a.backward(n).and_then(|x| x.backward(m)) == a.backward (n + m)` + /// * `a.backward(n)` equals `Step::predecessor` applied to `a` `n` times + /// * Corollary: `a.backward(0) == Some(a)` + /// * `a.backward(n).unwrap() <= a` + fn backward(&self, count: usize) -> Option; - /// Subtracts one to this step, returning the result. - fn sub_one(&self) -> Self; + /// Returns the *predecessor* of `self`. + /// + /// If this would underflow the range of values supported by `Self`, + /// this method is allowed to panic or wrap. Suggested behavior is + /// to panic when debug assertions are enabled, and wrap otherwise. + /// + /// # Invariants + /// + /// For any `a` where `a.predecessor()` does not underflow: + /// + /// * `a == a.predecessor().successor()` + /// * `a.predecessor() == a.backward(1).unwrap()` + /// * `a.predecessor() <= a` + #[inline] + #[unstable(feature = "step_trait_ext", reason = "recently added", issue = "42168")] + fn predecessor(&self) -> Self { + self.backward(1).expect("overflow in `Step::predecessor`") + } - /// Adds a `usize`, returning `None` on overflow. - fn add_usize(&self, n: usize) -> Option; + /// Returns the *predecessor* of `self`. + /// + /// If this would overflow the range of values supported by `Self`, + /// this method is defined to return the input value instead. + /// + /// # Invariants + /// + /// For any `a` where `a.predecessor()` does not overflow: + /// + /// * `a.predecessor_saturating() == a.predecessor()` + /// + /// For any `a` where `a.predecessor()` does overflow: + /// + /// * `a.predecessor_saturating() == a` + #[inline] + #[unstable(feature = "step_trait_ext", reason = "recently added", issue = "42168")] + fn predecessor_saturating(&self) -> Self { + self.backward(1).unwrap_or_else(|| self.clone()) + } - /// Subtracts a `usize`, returning `None` on underflow. - fn sub_usize(&self, n: usize) -> Option { - // this default implementation makes the addition of `sub_usize` a non-breaking change - let _ = n; - unimplemented!() + /// Returns the *predecessor* of `self`. + /// + /// # Safety + /// + /// It is undefined behavior if this operation exceeds the range of + /// values supported by `Self`. If you cannot guarantee that this + /// will not overflow, use `backward` or `predecessor` instead. + /// + /// For any `a`, if there exists `b` such that `b < a`, + /// it is safe to call `a.predecessor_unchecked()`. + #[inline] + #[unstable(feature = "unchecked_math", reason = "niche optimization path", issue = "none")] + unsafe fn predecessor_unchecked(&self) -> Self { + self.predecessor() } } @@ -53,127 +179,234 @@ pub trait Step: Clone + PartialOrd + Sized { macro_rules! step_identical_methods { () => { #[inline] - fn replace_one(&mut self) -> Self { - mem::replace(self, 1) + fn successor(&self) -> Self { + Add::add(*self, 1) } #[inline] - fn replace_zero(&mut self) -> Self { - mem::replace(self, 0) + fn successor_saturating(&self) -> Self { + Self::saturating_add(*self, 1) } #[inline] - fn add_one(&self) -> Self { - Add::add(*self, 1) + unsafe fn successor_unchecked(&self) -> Self { + Self::unchecked_add(*self, 1) } #[inline] - fn sub_one(&self) -> Self { + fn predecessor(&self) -> Self { Sub::sub(*self, 1) } + + #[inline] + fn predecessor_saturating(&self) -> Self { + Self::saturating_sub(*self, 1) + } + + #[inline] + unsafe fn predecessor_unchecked(&self) -> Self { + Self::unchecked_sub(*self, 1) + } } } -macro_rules! step_impl_unsigned { - ($($t:ty)*) => ($( - #[unstable(feature = "step_trait", - reason = "likely to be replaced by finer-grained traits", - issue = "42168")] - impl Step for $t { - #[inline] - fn steps_between(start: &$t, end: &$t) -> Option { - if *start < *end { - usize::try_from(*end - *start).ok() - } else { - Some(0) +macro_rules! step_integer_impls { + ( + narrower than or same width as usize: + $( [ $narrower_unsigned:ident $narrower_signed:ident ] ),+; + wider than usize: + $( [ $wider_unsigned:ident $wider_signed:ident ] ),+; + ) => { + $( + #[unstable( + feature = "step_trait", + reason = "recently redesigned", + issue = "42168" + )] + unsafe impl Step for $narrower_unsigned { + #[inline] + fn steps_between(start: &Self, end: &Self) -> Option { + if *start <= *end { + // This relies on $narrower_unsigned <= usize + Some((*end - *start) as usize) + } else { + None + } } - } - #[inline] - #[allow(unreachable_patterns)] - fn add_usize(&self, n: usize) -> Option { - match <$t>::try_from(n) { - Ok(n_as_t) => self.checked_add(n_as_t), - Err(_) => None, + #[inline] + #[allow(unreachable_patterns)] + fn forward(&self, n: usize) -> Option { + match Self::try_from(n) { + Ok(n_converted) => self.checked_add(n_converted), + Err(_) => None, // if n is out of range, `something_unsigned + n` is too + } } - } - #[inline] - #[allow(unreachable_patterns)] - fn sub_usize(&self, n: usize) -> Option { - match <$t>::try_from(n) { - Ok(n_as_t) => self.checked_sub(n_as_t), - Err(_) => None, + #[inline] + #[allow(unreachable_patterns)] + fn backward(&self, n: usize) -> Option { + match Self::try_from(n) { + Ok(n_converted) => self.checked_sub(n_converted), + Err(_) => None, // if n is out of range, `something_in_range - n` is too + } } + + step_identical_methods!(); } - step_identical_methods!(); - } - )*) -} -macro_rules! step_impl_signed { - ($( [$t:ty : $unsigned:ty] )*) => ($( - #[unstable(feature = "step_trait", - reason = "likely to be replaced by finer-grained traits", - issue = "42168")] - impl Step for $t { - #[inline] - fn steps_between(start: &$t, end: &$t) -> Option { - if *start < *end { - // Use .wrapping_sub and cast to unsigned to compute the - // difference that may not fit inside the range of $t. - usize::try_from(end.wrapping_sub(*start) as $unsigned).ok() - } else { - Some(0) + #[unstable( + feature = "step_trait", + reason = "recently redesigned", + issue = "42168" + )] + unsafe impl Step for $narrower_signed { + #[inline] + fn steps_between(start: &Self, end: &Self) -> Option { + if *start <= *end { + // This relies on $narrower_signed <= usize + // + // Casting to isize extends the width but preserves the sign. + // Use wrapping_sub in isize space and cast to usize + // to compute the difference that may not fit inside the range of isize. + Some((*end as isize).wrapping_sub(*start as isize) as usize) + } else { + None + } } - } - #[inline] - #[allow(unreachable_patterns)] - fn add_usize(&self, n: usize) -> Option { - match <$unsigned>::try_from(n) { - Ok(n_as_unsigned) => { - // Wrapping in unsigned space handles cases like - // `-120_i8.add_usize(200) == Some(80_i8)`, - // even though 200_usize is out of range for i8. - let wrapped = (*self as $unsigned).wrapping_add(n_as_unsigned) as $t; - if wrapped >= *self { - Some(wrapped) - } else { - None // Addition overflowed + #[inline] + #[allow(unreachable_patterns)] + fn forward(&self, n: usize) -> Option { + match <$narrower_unsigned>::try_from(n) { + Ok(n_unsigned) => { + // Wrapping in unsigned space handles cases like + // `-120_i8.forward(200) == Some(80_i8)`, + // even though 200_usize is out of range for i8. + let self_unsigned = *self as $narrower_unsigned; + let wrapped = self_unsigned.wrapping_add(n_unsigned) as Self; + if wrapped >= *self { + Some(wrapped) + } else { + None // Addition overflowed + } } + // If n is out of range of e.g. u8, + // then it is bigger than the entire range for i8 is wide + // so `any_i8 + n` would overflow i8. + Err(_) => None, } - Err(_) => None, } + + #[inline] + #[allow(unreachable_patterns)] + fn backward(&self, n: usize) -> Option { + match <$narrower_unsigned>::try_from(n) { + Ok(n_unsigned) => { + // Wrapping in unsigned space handles cases like + // `-120_i8.forward(200) == Some(80_i8)`, + // even though 200_usize is out of range for i8. + let self_unsigned = *self as $narrower_unsigned; + let wrapped = self_unsigned.wrapping_sub(n_unsigned) as Self; + if wrapped <= *self { + Some(wrapped) + } else { + None // Subtraction underflowed + } + } + // If n is out of range of e.g. u8, + // then it is bigger than the entire range for i8 is wide + // so `any_i8 - n` would underflow i8. + Err(_) => None, + } + } + + step_identical_methods!(); + } + )+ + + $( + #[unstable( + feature = "step_trait", + reason = "recently redesigned", + issue = "42168" + )] + unsafe impl Step for $wider_unsigned { + #[inline] + fn steps_between(start: &Self, end: &Self) -> Option { + if *start <= *end { + usize::try_from(*end - *start).ok() + } else { + None + } + } + + #[inline] + fn forward(&self, n: usize) -> Option { + self.checked_add(n as Self) + } + + #[inline] + fn backward(&self, n: usize) -> Option { + self.checked_sub(n as Self) + } + + step_identical_methods!(); } - #[inline] - #[allow(unreachable_patterns)] - fn sub_usize(&self, n: usize) -> Option { - match <$unsigned>::try_from(n) { - Ok(n_as_unsigned) => { - // Wrapping in unsigned space handles cases like - // `80_i8.sub_usize(200) == Some(-120_i8)`, - // even though 200_usize is out of range for i8. - let wrapped = (*self as $unsigned).wrapping_sub(n_as_unsigned) as $t; - if wrapped <= *self { - Some(wrapped) - } else { - None // Subtraction underflowed + #[unstable( + feature = "step_trait", + reason = "recently redesigned", + issue = "42168" + )] + unsafe impl Step for $wider_signed { + #[inline] + fn steps_between(start: &Self, end: &Self) -> Option { + if *start <= *end { + match end.checked_sub(*start) { + Some(diff) => usize::try_from(diff).ok(), + // If the difference is too big for e.g. i128, + // it’s also gonna be too big for usize with fewer bits. + None => None } + } else { + None } - Err(_) => None, } + + #[inline] + fn forward(&self, n: usize) -> Option { + self.checked_add(n as Self) + } + + #[inline] + fn backward(&self, n: usize) -> Option { + self.checked_sub(n as Self) + } + + step_identical_methods!(); } + )+ + } +} - step_identical_methods!(); - } - )*) +#[cfg(target_pointer_width = "64")] +step_integer_impls! { + narrower than or same width as usize: [u8 i8], [u16 i16], [u32 i32], [u64 i64], [usize isize]; + wider than usize: [u128 i128]; } -step_impl_unsigned!(usize u8 u16 u32 u64 u128); -step_impl_signed!([isize: usize][i8: u8][i16: u16]); -step_impl_signed!([i32: u32][i64: u64][i128: u128]); +#[cfg(target_pointer_width = "32")] +step_integer_impls! { + narrower than or same width as usize: [u8 i8], [u16 i16], [u32 i32], [usize isize]; + wider than usize: [u64 i64], [u128 i128]; +} + +#[cfg(target_pointer_width = "16")] +step_integer_impls! { + narrower than or same width as usize: [u8 i8], [u16 i16], [usize isize]; + wider than usize: [u32 i32], [u64 i64], [u128 i128]; +} macro_rules! range_exact_iter_impl { ($($t:ty)*) => ($( @@ -189,20 +422,6 @@ macro_rules! range_incl_exact_iter_impl { )*) } -macro_rules! range_trusted_len_impl { - ($($t:ty)*) => ($( - #[unstable(feature = "trusted_len", issue = "37572")] - unsafe impl TrustedLen for ops::Range<$t> { } - )*) -} - -macro_rules! range_incl_trusted_len_impl { - ($($t:ty)*) => ($( - #[unstable(feature = "trusted_len", issue = "37572")] - unsafe impl TrustedLen for ops::RangeInclusive<$t> { } - )*) -} - #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ops::Range { type Item = A; @@ -210,16 +429,10 @@ impl Iterator for ops::Range { #[inline] fn next(&mut self) -> Option { if self.start < self.end { - // We check for overflow here, even though it can't actually - // happen. Adding this check does however help llvm vectorize loops - // for some ranges that don't get vectorized otherwise, - // and this won't actually result in an extra check in an optimized build. - if let Some(mut n) = self.start.add_usize(1) { - mem::swap(&mut n, &mut self.start); - Some(n) - } else { - None - } + // SAFETY: just checked precondition + let mut n = unsafe { self.start.successor_unchecked() }; + mem::swap(&mut n, &mut self.start); + Some(n) } else { None } @@ -227,17 +440,20 @@ impl Iterator for ops::Range { #[inline] fn size_hint(&self) -> (usize, Option) { - match Step::steps_between(&self.start, &self.end) { - Some(hint) => (hint, Some(hint)), - None => (usize::MAX, None), + if self.start < self.end { + let hint = Step::steps_between(&self.start, &self.end); + (hint.unwrap_or(usize::MAX), hint) + } else { + (0, Some(0)) } } #[inline] fn nth(&mut self, n: usize) -> Option { - if let Some(plus_n) = self.start.add_usize(n) { + if let Some(plus_n) = self.start.forward(n) { if plus_n < self.end { - self.start = plus_n.add_one(); + // SAFETY: just checked precondition + self.start = unsafe { plus_n.successor_unchecked() }; return Some(plus_n); } } @@ -263,25 +479,43 @@ impl Iterator for ops::Range { } // These macros generate `ExactSizeIterator` impls for various range types. -// Range<{u,i}64> and RangeInclusive<{u,i}{32,64,size}> are excluded -// because they cannot guarantee having a length <= usize::MAX, which is -// required by ExactSizeIterator. -range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32); -range_incl_exact_iter_impl!(u8 u16 i8 i16); - -// These macros generate `TrustedLen` impls. // -// They need to guarantee that .size_hint() is either exact, or that -// the upper bound is None when it does not fit the type limits. -range_trusted_len_impl!(usize isize u8 i8 u16 i16 u32 i32 u64 i64 u128 i128); -range_incl_trusted_len_impl!(usize isize u8 i8 u16 i16 u32 i32 u64 i64 u128 i128); +// * `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`. +range_exact_iter_impl! { + usize u8 u16 + isize i8 i16 + + // These are incorect per the reasoning above, + // but removing them would be a breaking change as they were stabilized in Rust 1.0.0. + // So e.g. `(0..66_000_u32).len()` for example will compile without error or warnings + // on 16-bit platforms, but continue to give a wrong result. + u32 + i32 +} +range_incl_exact_iter_impl! { + u8 + i8 + + // These are incorect per the reasoning above, + // but removing them would be a breaking change as they were stabilized in Rust 1.26.0. + // So e.g. `(0..=u16::MAX).len()` for example will compile without error or warnings + // on 16-bit platforms, but continue to give a wrong result. + u16 + i16 +} #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for ops::Range { #[inline] fn next_back(&mut self) -> Option { if self.start < self.end { - self.end = self.end.sub_one(); + // SAFETY: just checked precondition + self.end = unsafe { self.end.predecessor_unchecked() }; Some(self.end.clone()) } else { None @@ -290,9 +524,10 @@ impl DoubleEndedIterator for ops::Range { #[inline] fn nth_back(&mut self, n: usize) -> Option { - if let Some(minus_n) = self.end.sub_usize(n) { + if let Some(minus_n) = self.end.backward(n) { if minus_n > self.start { - self.end = minus_n.sub_one(); + // SAFETY: just checked precondition + self.end = unsafe { minus_n.predecessor_unchecked() }; return Some(self.end.clone()); } } @@ -302,6 +537,9 @@ impl DoubleEndedIterator for ops::Range { } } +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for ops::Range {} + #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for ops::Range {} @@ -311,7 +549,13 @@ impl Iterator for ops::RangeFrom { #[inline] fn next(&mut self) -> Option { - let mut n = self.start.add_one(); + // This case is tricky. Consider `RangeFrom { start: 255_u8 }`. + // Ideally, we would return `255`, and then panic on the next call. + // Unfortunately, this is impossible as we don't have anywhere to + // store that information. This does debug-checked addition, so in + // debug mode, we panic instead of yielding 255, and in release mode, + // we wrap around the number space. + let mut n = self.start.successor(); mem::swap(&mut n, &mut self.start); Some(n) } @@ -323,8 +567,12 @@ impl Iterator for ops::RangeFrom { #[inline] fn nth(&mut self, n: usize) -> Option { - let plus_n = self.start.add_usize(n).expect("overflow in RangeFrom::nth"); - self.start = plus_n.add_one(); + // If we would jump over the maximum value, just panic immediately. + // This is consistent with behavior before the Step redesign, + // even though it's inconsistent with n `next` calls. + let plus_n = self.start.forward(n).expect("overflow in `RangeFrom::nth`"); + // Now we call `successor` to get debug-checked behavior for the final step. + self.start = plus_n.successor(); Some(plus_n) } } @@ -348,7 +596,8 @@ impl Iterator for ops::RangeInclusive { let is_iterating = self.start < self.end; self.is_empty = Some(!is_iterating); Some(if is_iterating { - let n = self.start.add_one(); + // SAFETY: just checked precondition + let n = unsafe { self.start.successor_unchecked() }; mem::replace(&mut self.start, n) } else { self.start.clone() @@ -374,13 +623,14 @@ impl Iterator for ops::RangeInclusive { return None; } - if let Some(plus_n) = self.start.add_usize(n) { + if let Some(plus_n) = self.start.forward(n) { use crate::cmp::Ordering::*; match plus_n.partial_cmp(&self.end) { Some(Less) => { self.is_empty = Some(false); - self.start = plus_n.add_one(); + // SAFETY: just checked precondition + self.start = unsafe { plus_n.successor_unchecked() }; return Some(plus_n); } Some(Equal) => { @@ -411,7 +661,8 @@ impl Iterator for ops::RangeInclusive { let mut accum = init; while self.start < self.end { - let n = self.start.add_one(); + // SAFETY: just checked precondition + let n = unsafe { self.start.successor_unchecked() }; let n = mem::replace(&mut self.start, n); accum = f(accum, n)?; } @@ -452,7 +703,8 @@ impl DoubleEndedIterator for ops::RangeInclusive { let is_iterating = self.start < self.end; self.is_empty = Some(!is_iterating); Some(if is_iterating { - let n = self.end.sub_one(); + // SAFETY: just checked precondition + let n = unsafe { self.end.predecessor_unchecked() }; mem::replace(&mut self.end, n) } else { self.end.clone() @@ -466,13 +718,14 @@ impl DoubleEndedIterator for ops::RangeInclusive { return None; } - if let Some(minus_n) = self.end.sub_usize(n) { + if let Some(minus_n) = self.end.backward(n) { use crate::cmp::Ordering::*; match minus_n.partial_cmp(&self.start) { Some(Greater) => { self.is_empty = Some(false); - self.end = minus_n.sub_one(); + // SAFETY: just checked precondition + self.end = unsafe { minus_n.predecessor_unchecked() }; return Some(minus_n); } Some(Equal) => { @@ -503,7 +756,8 @@ impl DoubleEndedIterator for ops::RangeInclusive { let mut accum = init; while self.start < self.end { - let n = self.end.sub_one(); + // SAFETY: just checked precondition + let n = unsafe { self.end.predeccessor_unchecked() }; let n = mem::replace(&mut self.end, n); accum = f(accum, n)?; } @@ -518,5 +772,8 @@ impl DoubleEndedIterator for ops::RangeInclusive { } } +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for ops::RangeInclusive {} + #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for ops::RangeInclusive {} diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 39c7d6d24ed04..4ec68b4ab0063 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -710,6 +710,23 @@ $EndFeature, " } } + doc_comment! { + concat!("Unchecked integer addition. Computes `self + rhs, assuming overflow +cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT), +"::max_value()` or `self + rhs < ", stringify!($SelfT), "::min_value()`."), + #[unstable( + feature = "unchecked_math", + reason = "niche optimization path", + issue = "none", + )] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub unsafe fn unchecked_add(self, rhs: Self) -> Self { + intrinsics::unchecked_add(self, rhs) + } + } + doc_comment! { concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred. @@ -734,6 +751,23 @@ $EndFeature, " } } + doc_comment! { + concat!("Unchecked integer subtraction. Computes `self - rhs, assuming overflow +cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT), +"::max_value()` or `self - rhs < ", stringify!($SelfT), "::min_value()`."), + #[unstable( + feature = "unchecked_math", + reason = "niche optimization path", + issue = "none", + )] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub unsafe fn unchecked_sub(self, rhs: Self) -> Self { + intrinsics::unchecked_sub(self, rhs) + } + } + doc_comment! { concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred. @@ -758,6 +792,23 @@ $EndFeature, " } } + doc_comment! { + concat!("Unchecked integer multiplication. Computes `self * rhs, assuming overflow +cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT), +"::max_value()` or `self * rhs < ", stringify!($SelfT), "::min_value()`."), + #[unstable( + feature = "unchecked_math", + reason = "niche optimization path", + issue = "none", + )] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub unsafe fn unchecked_mul(self, rhs: Self) -> Self { + intrinsics::unchecked_mul(self, rhs) + } + } + doc_comment! { concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or the division results in overflow. @@ -2856,6 +2907,23 @@ assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", } } + doc_comment! { + concat!("Unchecked integer addition. Computes `self + rhs, assuming overflow +cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT), +"::max_value()` or `self + rhs < ", stringify!($SelfT), "::min_value()`."), + #[unstable( + feature = "unchecked_math", + reason = "niche optimization path", + issue = "none", + )] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub unsafe fn unchecked_add(self, rhs: Self) -> Self { + intrinsics::unchecked_add(self, rhs) + } + } + doc_comment! { concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred. @@ -2878,6 +2946,23 @@ assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, " } } + doc_comment! { + concat!("Unchecked integer subtraction. Computes `self - rhs, assuming overflow +cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT), +"::max_value()` or `self - rhs < ", stringify!($SelfT), "::min_value()`."), + #[unstable( + feature = "unchecked_math", + reason = "niche optimization path", + issue = "none", + )] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub unsafe fn unchecked_sub(self, rhs: Self) -> Self { + intrinsics::unchecked_sub(self, rhs) + } + } + doc_comment! { concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred. @@ -2900,6 +2985,23 @@ assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFe } } + doc_comment! { + concat!("Unchecked integer multiplication. Computes `self * rhs, assuming overflow +cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT), +"::max_value()` or `self * rhs < ", stringify!($SelfT), "::min_value()`."), + #[unstable( + feature = "unchecked_math", + reason = "niche optimization path", + issue = "none", + )] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub unsafe fn unchecked_mul(self, rhs: Self) -> Self { + intrinsics::unchecked_mul(self, rhs) + } + } + doc_comment! { concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`. diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index bd3218ec27f32..355787031fb5d 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -2,7 +2,7 @@ use core::cell::Cell; use core::convert::TryFrom; use core::iter::*; use core::usize; -use core::{i16, i8, isize}; +use core::{i128, i16, i8, isize, u128, u16, usize}; #[test] fn test_lt() { @@ -2110,6 +2110,24 @@ fn test_range_inclusive_nth_back() { assert_eq!(ExactSizeIterator::is_empty(&r), true); } +#[test] +fn test_range_len() { + assert_eq!((0..10_u8).len(), 10); + assert_eq!((9..10_u8).len(), 1); + assert_eq!((10..10_u8).len(), 0); + assert_eq!((11..10_u8).len(), 0); + assert_eq!((100..10_u8).len(), 0); +} + +#[test] +fn test_range_inclusive_len() { + assert_eq!((0..=10_u8).len(), 11); + assert_eq!((9..=10_u8).len(), 2); + assert_eq!((10..=10_u8).len(), 1); + assert_eq!((11..=10_u8).len(), 0); + assert_eq!((100..=10_u8).len(), 0); +} + #[test] fn test_range_step() { #![allow(deprecated)] @@ -2483,43 +2501,85 @@ fn test_chain_fold() { assert_eq!(&[2, 3, 1, 2, 0], &result[..]); } -#[test] -fn test_step_replace_unsigned() { - let mut x = 4u32; - let y = x.replace_zero(); - assert_eq!(x, 0); - assert_eq!(y, 4); +fn test_steps_between() { + assert_eq!(Step::steps_between(&20_u8, &200_u8), Some(180_usize)); + assert_eq!(Step::steps_between(&-20_i8, &80_i8), Some(100_usize)); + assert_eq!(Step::steps_between(&-120_i8, &80_i8), Some(200_usize)); + assert_eq!(Step::steps_between(&20_u32, &4_000_100_u32), Some(4_000_080_usize)); + assert_eq!(Step::steps_between(&-20_i32, &80_i32), Some(100_usize)); + assert_eq!(Step::steps_between(&-2_000_030_i32, &2_000_050_i32), Some(4_000_080_usize)); - x = 5; - let y = x.replace_one(); - assert_eq!(x, 1); - assert_eq!(y, 5); -} - -#[test] -fn test_step_replace_signed() { - let mut x = 4i32; - let y = x.replace_zero(); - assert_eq!(x, 0); - assert_eq!(y, 4); + // Skip u64/i64 to avoid differences with 32-bit vs 64-bit platforms - x = 5; - let y = x.replace_one(); - assert_eq!(x, 1); - assert_eq!(y, 5); + assert_eq!(Step::steps_between(&20_u128, &200_u128), Some(180_usize)); + assert_eq!(Step::steps_between(&-20_i128, &80_i128), Some(100_usize)); + if cfg!(target_pointer_width = "64") { + assert_eq!(Step::steps_between(&10_u128, &0x1_0000_0000_0000_0009_u128), Some(usize::MAX)); + } + assert_eq!(Step::steps_between(&10_u128, &0x1_0000_0000_0000_000a_u128), None); + assert_eq!(Step::steps_between(&10_i128, &0x1_0000_0000_0000_000a_i128), None); + assert_eq!( + Step::steps_between(&-0x1_0000_0000_0000_0000_i128, &0x1_0000_0000_0000_0000_i128,), + None, + ); } #[test] -fn test_step_replace_no_between() { - let mut x = 4u128; - let y = x.replace_zero(); - assert_eq!(x, 0); - assert_eq!(y, 4); +fn test_step_forward() { + assert_eq!((55_u8).forward(200_usize), Some(255_u8)); + assert_eq!((252_u8).forward(200_usize), None); + assert_eq!((0_u8).forward(256_usize), None); + assert_eq!((-110_i8).forward(200_usize), Some(90_i8)); + assert_eq!((-110_i8).forward(248_usize), None); + assert_eq!((-126_i8).forward(256_usize), None); - x = 5; - let y = x.replace_one(); - assert_eq!(x, 1); - assert_eq!(y, 5); + assert_eq!((35_u16).forward(100_usize), Some(135_u16)); + assert_eq!((35_u16).forward(65500_usize), Some(u16::MAX)); + assert_eq!((36_u16).forward(65500_usize), None); + assert_eq!((-110_i16).forward(200_usize), Some(90_i16)); + assert_eq!((-20_030_i16).forward(50_050_usize), Some(30_020_i16)); + assert_eq!((-10_i16).forward(40_000_usize), None); + assert_eq!((-10_i16).forward(70_000_usize), None); + + assert_eq!((10_u128).forward(70_000_usize), Some(70_010_u128)); + assert_eq!((10_i128).forward(70_030_usize), Some(70_040_i128)); + assert_eq!( + (0xffff_ffff_ffff_ffff__ffff_ffff_ffff_ff00_u128).forward(0xff_usize), + Some(u128::MAX), + ); + assert_eq!((0xffff_ffff_ffff_ffff__ffff_ffff_ffff_ff00_u128).forward(0x100_usize), None); + assert_eq!( + (0x7fff_ffff_ffff_ffff__ffff_ffff_ffff_ff00_i128).forward(0xff_usize), + Some(i128::MAX), + ); + assert_eq!((0x7fff_ffff_ffff_ffff__ffff_ffff_ffff_ff00_i128).forward(0x100_usize), None); +} + +#[test] +fn test_step_backward() { + assert_eq!((255_u8).backward(200_usize), Some(55_u8)); + assert_eq!((100_u8).backward(200_usize), None); + assert_eq!((255_u8).backward(256_usize), None); + assert_eq!((90_i8).backward(200_usize), Some(-110_i8)); + assert_eq!((110_i8).backward(248_usize), None); + assert_eq!((127_i8).backward(256_usize), None); + + assert_eq!((135_u16).backward(100_usize), Some(35_u16)); + assert_eq!((u16::MAX).backward(65500_usize), Some(35_u16)); + assert_eq!((10_u16).backward(11_usize), None); + assert_eq!((90_i16).backward(200_usize), Some(-110_i16)); + assert_eq!((30_020_i16).backward(50_050_usize), Some(-20_030_i16)); + assert_eq!((-10_i16).backward(40_000_usize), None); + assert_eq!((-10_i16).backward(70_000_usize), None); + + assert_eq!((70_010_u128).backward(70_000_usize), Some(10_u128)); + assert_eq!((70_020_i128).backward(70_030_usize), Some(-10_i128)); + assert_eq!((10_u128).backward(7_usize), Some(3_u128)); + assert_eq!((10_u128).backward(11_usize), None); + assert_eq!( + (-0x7fff_ffff_ffff_ffff__ffff_ffff_ffff_ff00_i128).backward(0x100_usize), + Some(i128::MIN) + ); } #[test] diff --git a/src/librustc_index/vec.rs b/src/librustc_index/vec.rs index d14bafb44fd5b..de7a43d35c4b8 100644 --- a/src/librustc_index/vec.rs +++ b/src/librustc_index/vec.rs @@ -200,7 +200,7 @@ macro_rules! newtype_index { } } - impl ::std::iter::Step for $type { + unsafe impl ::std::iter::Step for $type { #[inline] fn steps_between(start: &Self, end: &Self) -> Option { ::steps_between( @@ -210,32 +210,22 @@ macro_rules! newtype_index { } #[inline] - fn replace_one(&mut self) -> Self { - ::std::mem::replace(self, Self::from_u32(1)) - } - - #[inline] - fn replace_zero(&mut self) -> Self { - ::std::mem::replace(self, Self::from_u32(0)) - } - - #[inline] - fn add_one(&self) -> Self { + fn successor(&self) -> Self { Self::from_usize(Self::index(*self) + 1) } #[inline] - fn sub_one(&self) -> Self { + fn predecessor(&self) -> Self { Self::from_usize(Self::index(*self) - 1) } #[inline] - fn add_usize(&self, u: usize) -> Option { + fn forward(&self, u: usize) -> Option { Self::index(*self).checked_add(u).map(Self::from_usize) } #[inline] - fn sub_usize(&self, u: usize) -> Option { + fn backward(&self, u: usize) -> Option { Self::index(*self).checked_sub(u).map(Self::from_usize) } } diff --git a/src/test/ui/impl-trait/example-calendar.rs b/src/test/ui/impl-trait/example-calendar.rs index f1b1656745e7c..584c3f78fa046 100644 --- a/src/test/ui/impl-trait/example-calendar.rs +++ b/src/test/ui/impl-trait/example-calendar.rs @@ -2,6 +2,7 @@ #![feature(fn_traits, step_trait, + step_trait_ext, unboxed_closures, )] @@ -156,32 +157,20 @@ impl<'a, 'b> std::ops::Add<&'b NaiveDate> for &'a NaiveDate { } } -impl std::iter::Step for NaiveDate { +unsafe impl std::iter::Step for NaiveDate { fn steps_between(_: &Self, _: &Self) -> Option { unimplemented!() } - fn replace_one(&mut self) -> Self { - mem::replace(self, NaiveDate(0, 0, 1)) - } - - fn replace_zero(&mut self) -> Self { - mem::replace(self, NaiveDate(0, 0, 0)) - } - - fn add_one(&self) -> Self { + fn successor(&self) -> Self { self.succ() } - fn sub_one(&self) -> Self { - unimplemented!() - } - - fn add_usize(&self, _: usize) -> Option { + fn forward(&self, _: usize) -> Option { unimplemented!() } - fn sub_usize(&self, _: usize) -> Option { + fn backward(&self, _: usize) -> Option { unimplemented!() } }