Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 2073441

Browse files
committed
unwrap in SliceIndex<usize>::get_unchecked instead
1 parent 26611b4 commit 2073441

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

library/core/src/slice/index.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ unsafe impl<T> SliceIndex<[T]> for usize {
214214
#[inline]
215215
fn get(self, slice: &[T]) -> Option<&T> {
216216
// SAFETY: `self` is checked to be in bounds.
217-
if self < slice.len() { unsafe { Some(&*self.get_unchecked(slice)) } } else { None }
217+
// The call to `add` is safe, as we check the bounds.
218+
if self < slice.len() { unsafe { Some(&*slice.as_ptr().add(self)) } } else { None }
218219
}
219220

220221
#[inline]
@@ -229,13 +230,14 @@ unsafe impl<T> SliceIndex<[T]> for usize {
229230
// SAFETY: the caller guarantees that `slice` is not dangling, so it
230231
// cannot be longer than `isize::MAX`. They also guarantee that
231232
// `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
232-
// so the call to `add` is safe.
233+
// so we can `unwrap_unchecked`.
234+
// We use `get().unwrap_unchecked()` for better codegen: see issue #116878
233235
unsafe {
234236
assert_unsafe_precondition!(
235237
"slice::get_unchecked requires that the index is within the slice",
236238
[T](this: usize, slice: *const [T]) => this < slice.len()
237239
);
238-
slice.as_ptr().add(self)
240+
self.get(&*slice).unwrap_unchecked() as *const _
239241
}
240242
}
241243

library/core/src/slice/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,7 @@ impl<T> [T] {
662662
// SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
663663
// the slice is dereferenceable because `self` is a safe reference.
664664
// The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
665-
unsafe { &*index.get(self).unwrap_unchecked() }
665+
unsafe { &*index.get_unchecked(self) }
666666
}
667667

668668
/// Returns a mutable reference to an element or subslice, without doing

0 commit comments

Comments
 (0)