Skip to content

Commit 9f549da

Browse files
committed
more const methods on str
1 parent e454c45 commit 9f549da

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

Diff for: library/core/src/str/mod.rs

+40-3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
1717
use crate::char::{self, EscapeDebugExtArgs};
1818
use crate::ops::Range;
1919
use crate::slice::{self, SliceIndex};
20+
use crate::ub_checks::assert_unsafe_precondition;
2021
use crate::{ascii, mem};
2122

2223
pub mod pattern;
@@ -720,7 +721,7 @@ impl str {
720721
// is_char_boundary checks that the index is in [0, .len()]
721722
if self.is_char_boundary(mid) {
722723
// SAFETY: just checked that `mid` is on a char boundary.
723-
Some(unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) })
724+
Some(unsafe { self.split_at_unchecked(mid) })
724725
} else {
725726
None
726727
}
@@ -766,15 +767,51 @@ impl str {
766767
}
767768
}
768769

769-
/// Divides one string slice into two at an index.
770+
/// Divides one string slice into two immutable slices at an index.
771+
///
772+
/// # Safety
773+
///
774+
/// The caller must ensure that `mid` is a valid byte offset from the start
775+
/// of the string and falls on the boundary of a UTF-8 code point.
776+
#[inline]
777+
#[must_use]
778+
const unsafe fn split_at_unchecked(&self, mid: usize) -> (&str, &str) {
779+
let len = self.len();
780+
let ptr = self.as_ptr();
781+
782+
assert_unsafe_precondition!(
783+
check_library_ub,
784+
"str::split_at_unchecked requires the index to be within the slice",
785+
(mid: usize = mid, len: usize = len) => mid <= len,
786+
);
787+
788+
// SAFETY: caller guarantees `mid` is on a char boundary.
789+
unsafe {
790+
(
791+
from_utf8_unchecked(slice::from_raw_parts(ptr, mid)),
792+
from_utf8_unchecked(slice::from_raw_parts(ptr.add(mid), len - mid)),
793+
)
794+
}
795+
}
796+
797+
/// Divides one string slice into two mutable slices at an index.
770798
///
771799
/// # Safety
772800
///
773801
/// The caller must ensure that `mid` is a valid byte offset from the start
774802
/// of the string and falls on the boundary of a UTF-8 code point.
775-
unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) {
803+
#[inline]
804+
#[must_use]
805+
const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) {
776806
let len = self.len();
777807
let ptr = self.as_mut_ptr();
808+
809+
assert_unsafe_precondition!(
810+
check_library_ub,
811+
"str::split_at_mut_unchecked requires the index to be within the slice",
812+
(mid: usize = mid, len: usize = len) => mid <= len,
813+
);
814+
778815
// SAFETY: caller guarantees `mid` is on a char boundary.
779816
unsafe {
780817
(

0 commit comments

Comments
 (0)