Skip to content

Commit 439d83d

Browse files
committed
add split_at_unchecked
1 parent 67adea8 commit 439d83d

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

library/core/src/str/mod.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,33 @@ impl str {
766766
}
767767
}
768768

769+
/// Divides one string slice into two immutable slices at an index.
770+
///
771+
/// # Safety
772+
///
773+
/// The caller must ensure that `mid` is a valid byte offset from the start
774+
/// of the string and falls on the boundary of a UTF-8 code point.
775+
#[inline]
776+
#[must_use]
777+
unsafe const fn split_at_unchecked(&self, mid: usize) -> (&str, &str) {
778+
let len = self.len();
779+
let ptr = self.as_ptr();
780+
781+
assert_unsafe_precondition!(
782+
check_library_ub,
783+
"str::split_at_unchecked requires the index to be within the slice",
784+
(mid: usize = mid, len: usize = len) => mid <= len,
785+
);
786+
787+
// SAFETY: caller guarantees `mid` is on a char boundary.
788+
unsafe {
789+
(
790+
from_utf8_unchecked_mut(slice::from_raw_parts(ptr, mid)),
791+
from_utf8_unchecked_mut(slice::from_raw_parts(ptr.add(mid), len - mid)),
792+
)
793+
}
794+
}
795+
769796
/// Divides one string slice into two mutable slices at an index.
770797
///
771798
/// # Safety
@@ -780,7 +807,7 @@ impl str {
780807

781808
assert_unsafe_precondition!(
782809
check_library_ub,
783-
"slice::split_at_mut_unchecked requires the index to be within the slice",
810+
"str::split_at_mut_unchecked requires the index to be within the slice",
784811
(mid: usize = mid, len: usize = len) => mid <= len,
785812
);
786813

0 commit comments

Comments
 (0)