Skip to content

Commit 3f40a9d

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 3d8c1c1 commit 3f40a9d

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
@@ -652,7 +652,6 @@ unsafe impl<T> const SliceIndex<[T]> for ops::RangeFull {
652652
}
653653

654654
/// The methods `index` and `index_mut` panic if:
655-
/// - the end of the range is `usize::MAX` or
656655
/// - the start of the range is greater than the end of the range or
657656
/// - the end of the range is out of bounds.
658657
#[stable(feature = "inclusive_range", since = "1.26.0")]
@@ -662,12 +661,14 @@ unsafe impl<T> const SliceIndex<[T]> for ops::RangeInclusive<usize> {
662661

663662
#[inline]
664663
fn get(self, slice: &[T]) -> Option<&[T]> {
665-
if *self.end() == usize::MAX { None } else { self.into_slice_range().get(slice) }
664+
// `self.into_slice_range()` cannot overflow, because `*self.end() <
665+
// slice.len()` implies `*self.end() < usize::MAX`.
666+
if *self.end() >= slice.len() { None } else { self.into_slice_range().get(slice) }
666667
}
667668

668669
#[inline]
669670
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
670-
if *self.end() == usize::MAX { None } else { self.into_slice_range().get_mut(slice) }
671+
if *self.end() >= slice.len() { None } else { self.into_slice_range().get_mut(slice) }
671672
}
672673

673674
#[inline]

0 commit comments

Comments
 (0)