Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2b2e8e7

Browse files
committedSep 11, 2024
Expand assumes to the other unchecked slice ops
1 parent f827364 commit 2b2e8e7

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed
 

‎library/core/src/slice/index.rs

+12-3
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,10 @@ unsafe impl<T> SliceIndex<[T]> for usize {
293293
(this: usize = self, len: usize = slice.len()) => this < len
294294
);
295295
// SAFETY: see comments for `get_unchecked` above.
296-
unsafe { get_mut_noubcheck(slice, self) }
296+
unsafe {
297+
crate::hint::assert_unchecked(self < slice.len());
298+
get_mut_noubcheck(slice, self)
299+
}
297300
}
298301

299302
#[inline]
@@ -346,7 +349,10 @@ unsafe impl<T> SliceIndex<[T]> for ops::IndexRange {
346349
// cannot be longer than `isize::MAX`. They also guarantee that
347350
// `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
348351
// so the call to `add` is safe.
349-
unsafe { get_offset_len_noubcheck(slice, self.start(), self.len()) }
352+
unsafe {
353+
crate::intrinsics::assume(self.end() <= slice.len());
354+
get_offset_len_noubcheck(slice, self.start(), self.len())
355+
}
350356
}
351357

352358
#[inline]
@@ -358,7 +364,10 @@ unsafe impl<T> SliceIndex<[T]> for ops::IndexRange {
358364
);
359365

360366
// SAFETY: see comments for `get_unchecked` above.
361-
unsafe { get_offset_len_mut_noubcheck(slice, self.start(), self.len()) }
367+
unsafe {
368+
crate::intrinsics::assume(self.end() <= slice.len());
369+
get_offset_len_mut_noubcheck(slice, self.start(), self.len())
370+
}
362371
}
363372

364373
#[inline]

‎tests/codegen/issues/issue-116878.rs

+24
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,27 @@ pub unsafe fn unchecked_slice_no_bounds_check(s: &[u8]) -> u8 {
99
// CHECK-NOT: panic_bounds_check
1010
a + s[0]
1111
}
12+
13+
// CHECK-LABEL: @unchecked_slice_no_bounds_check_mut
14+
#[no_mangle]
15+
pub unsafe fn unchecked_slice_no_bounds_check_mut(s: &mut [u8]) -> u8 {
16+
let a = *s.get_unchecked_mut(2);
17+
// CHECK-NOT: panic_bounds_check
18+
a + s[1]
19+
}
20+
21+
// CHECK-LABEL: @unchecked_slice_no_bounds_check_range
22+
#[no_mangle]
23+
pub unsafe fn unchecked_slice_no_bounds_check_range(s: &[u8]) -> u8 {
24+
let _a = &s.get_unchecked(..1);
25+
// CHECK-NOT: panic_bounds_check
26+
s[0]
27+
}
28+
29+
// CHECK-LABEL: @unchecked_slice_no_bounds_check_range_mut
30+
#[no_mangle]
31+
pub unsafe fn unchecked_slice_no_bounds_check_range_mut(s: &mut [u8]) -> u8 {
32+
let _a = &mut s.get_unchecked_mut(..2);
33+
// CHECK-NOT: panic_bounds_check
34+
s[1]
35+
}

0 commit comments

Comments
 (0)
Failed to load comments.