Skip to content

Commit cc2f0a0

Browse files
committed
Use unchecked_sub in str indexing
1 parent 7385447 commit cc2f0a0

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

core/src/str/traits.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Trait implementations for `str`.
22
33
use crate::cmp::Ordering;
4+
use crate::intrinsics::unchecked_sub;
45
use crate::ops;
56
use crate::ptr;
67
use crate::slice::SliceIndex;
@@ -210,9 +211,10 @@ unsafe impl SliceIndex<str> for ops::Range<usize> {
210211

211212
// SAFETY: the caller guarantees that `self` is in bounds of `slice`
212213
// which satisfies all the conditions for `add`.
213-
let ptr = unsafe { slice.as_ptr().add(self.start) };
214-
let len = self.end - self.start;
215-
ptr::slice_from_raw_parts(ptr, len) as *const str
214+
unsafe {
215+
let new_len = unchecked_sub(self.end, self.start);
216+
ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), new_len) as *const str
217+
}
216218
}
217219
#[inline]
218220
unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output {
@@ -229,9 +231,10 @@ unsafe impl SliceIndex<str> for ops::Range<usize> {
229231
);
230232

231233
// SAFETY: see comments for `get_unchecked`.
232-
let ptr = unsafe { slice.as_mut_ptr().add(self.start) };
233-
let len = self.end - self.start;
234-
ptr::slice_from_raw_parts_mut(ptr, len) as *mut str
234+
unsafe {
235+
let new_len = unchecked_sub(self.end, self.start);
236+
ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), new_len) as *mut str
237+
}
235238
}
236239
#[inline]
237240
fn index(self, slice: &str) -> &Self::Output {

0 commit comments

Comments
 (0)