Skip to content

Commit ee0e00a

Browse files
committed
Auto merge of #108763 - scottmcm:indexing-nuw-lengths, r=cuviper
Use `nuw` when calculating slice lengths from `Range`s An `assume` would definitely not be worth it, but since the flag is almost free we might as well tell LLVM this, especially on `_unchecked` calls where there's no obvious way for it to deduce it. (Today neither safe nor unsafe indexing gets it: <https://rust.godbolt.org/z/G1jYT548s>)
2 parents 51ff583 + b55cbf7 commit ee0e00a

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

core/src/slice/index.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use crate::intrinsics::assert_unsafe_precondition;
44
use crate::intrinsics::const_eval_select;
5+
use crate::intrinsics::unchecked_sub;
56
use crate::ops;
67
use crate::ptr;
78

@@ -375,14 +376,15 @@ unsafe impl<T> const SliceIndex<[T]> for ops::Range<usize> {
375376
// SAFETY: the caller guarantees that `slice` is not dangling, so it
376377
// cannot be longer than `isize::MAX`. They also guarantee that
377378
// `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
378-
// so the call to `add` is safe.
379+
// so the call to `add` is safe and the length calculation cannot overflow.
379380
unsafe {
380381
assert_unsafe_precondition!(
381382
"slice::get_unchecked requires that the range is within the slice",
382383
[T](this: ops::Range<usize>, slice: *const [T]) =>
383384
this.end >= this.start && this.end <= slice.len()
384385
);
385-
ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
386+
let new_len = unchecked_sub(self.end, self.start);
387+
ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), new_len)
386388
}
387389
}
388390

@@ -396,7 +398,8 @@ unsafe impl<T> const SliceIndex<[T]> for ops::Range<usize> {
396398
[T](this: ops::Range<usize>, slice: *mut [T]) =>
397399
this.end >= this.start && this.end <= slice.len()
398400
);
399-
ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
401+
let new_len = unchecked_sub(self.end, self.start);
402+
ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), new_len)
400403
}
401404
}
402405

0 commit comments

Comments
 (0)