about summary refs log tree commit diff
path: root/library/core/src/str
diff options
context:
space:
mode:
authorBen Kimock <kimockb@gmail.com>2024-04-06 11:33:09 -0400
committerBen Kimock <kimockb@gmail.com>2024-04-06 14:09:03 -0400
commit712aab72df2a9c511e49a51974294d3d2712056e (patch)
treec517516c5dec157524794d008aa9df45420647b8 /library/core/src/str
parent83d0a940c65e9c276308c81107b9b21cf399cbc6 (diff)
Use unchecked_sub in str indexing
Diffstat (limited to 'library/core/src/str')
-rw-r--r--library/core/src/str/traits.rs15
1 files changed, 9 insertions, 6 deletions
diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs
index 672af752149..ba2d6f64496 100644
--- a/library/core/src/str/traits.rs
+++ b/library/core/src/str/traits.rs
@@ -1,6 +1,7 @@
 //! Trait implementations for `str`.
 
 use crate::cmp::Ordering;
+use crate::intrinsics::unchecked_sub;
 use crate::ops;
 use crate::ptr;
 use crate::slice::SliceIndex;
@@ -210,9 +211,10 @@ unsafe impl SliceIndex<str> for ops::Range<usize> {
 
         // SAFETY: the caller guarantees that `self` is in bounds of `slice`
         // which satisfies all the conditions for `add`.
-        let ptr = unsafe { slice.as_ptr().add(self.start) };
-        let len = self.end - self.start;
-        ptr::slice_from_raw_parts(ptr, len) as *const str
+        unsafe {
+            let new_len = unchecked_sub(self.end, self.start);
+            ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), new_len) as *const str
+        }
     }
     #[inline]
     unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output {
@@ -229,9 +231,10 @@ unsafe impl SliceIndex<str> for ops::Range<usize> {
         );
 
         // SAFETY: see comments for `get_unchecked`.
-        let ptr = unsafe { slice.as_mut_ptr().add(self.start) };
-        let len = self.end - self.start;
-        ptr::slice_from_raw_parts_mut(ptr, len) as *mut str
+        unsafe {
+            let new_len = unchecked_sub(self.end, self.start);
+            ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), new_len) as *mut str
+        }
     }
     #[inline]
     fn index(self, slice: &str) -> &Self::Output {