Skip to content

Commit ce33804

Browse files
Fix panic message when RangeFrom index is out of bounds
Before, the `Range` method was called with `end = slice.len()`. Unfortunately, because `Range::index` first checks the order of the indices (start has to be smaller than end), an out of bounds index leads to `core::slice::slice_index_order_fail` being called. This prints the message 'slice index starts at 27 but ends at 10', which is worse than 'index 27 out of range for slice of length 10'. This is not only useful to normal users reading panic messages, but also for people inspecting assembly and being confused by `slice_index_order_fail` calls.
1 parent 47ea6d9 commit ce33804

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

src/libcore/slice/mod.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -3241,12 +3241,18 @@ unsafe impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
32413241

32423242
#[inline]
32433243
fn index(self, slice: &[T]) -> &[T] {
3244-
(self.start..slice.len()).index(slice)
3244+
if self.start > slice.len() {
3245+
slice_index_len_fail(self.start, slice.len());
3246+
}
3247+
unsafe { &*self.get_unchecked(slice) }
32453248
}
32463249

32473250
#[inline]
32483251
fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3249-
(self.start..slice.len()).index_mut(slice)
3252+
if self.start > slice.len() {
3253+
slice_index_len_fail(self.start, slice.len());
3254+
}
3255+
unsafe { &mut *self.get_unchecked_mut(slice) }
32503256
}
32513257
}
32523258

src/libcore/tests/slice.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1088,7 +1088,7 @@ mod slice_index {
10881088

10891089
good: data[6..] == [];
10901090
bad: data[7..];
1091-
message: "but ends at"; // perhaps not ideal
1091+
message: "out of range";
10921092
}
10931093

10941094
in mod rangeto_len {

0 commit comments

Comments
 (0)