Skip to content

Commit 57f1ce6

Browse files
committed
Optimize SliceIndex impl for RangeInclusive
The check for `self.end() == usize::MAX` can be combined with the `self.end() + 1 > slice.len()` check into `self.en() >= slice.len()`, since `self.end() < slice.len()` implies both `self.end() <= slice.len()` and `self.end() < usize::MAX`. The tradeoff is slightly worse error reporting: previously there would be a special panic message in the `range.end() == usize::MAX` case.
1 parent f5703d5 commit 57f1ce6

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

library/core/src/slice/index.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,6 @@ unsafe impl<T> const SliceIndex<[T]> for ops::RangeFull {
650650
}
651651

652652
/// The methods `index` and `index_mut` panic if:
653-
/// - the end of the range is `usize::MAX` or
654653
/// - the start of the range is greater than the end of the range or
655654
/// - the end of the range is out of bounds.
656655
#[stable(feature = "inclusive_range", since = "1.26.0")]
@@ -660,12 +659,14 @@ unsafe impl<T> const SliceIndex<[T]> for ops::RangeInclusive<usize> {
660659

661660
#[inline]
662661
fn get(self, slice: &[T]) -> Option<&[T]> {
663-
if *self.end() == usize::MAX { None } else { self.into_slice_range().get(slice) }
662+
// `self.into_slice_range()` cannot overflow, because `*self.end() <
663+
// slice.len()` implies `*self.end() < usize::MAX`.
664+
if *self.end() >= slice.len() { None } else { self.into_slice_range().get(slice) }
664665
}
665666

666667
#[inline]
667668
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
668-
if *self.end() == usize::MAX { None } else { self.into_slice_range().get_mut(slice) }
669+
if *self.end() >= slice.len() { None } else { self.into_slice_range().get_mut(slice) }
669670
}
670671

671672
#[inline]

0 commit comments

Comments
 (0)