@@ -17,6 +17,7 @@ use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
17
17
use crate :: char:: { self , EscapeDebugExtArgs } ;
18
18
use crate :: ops:: Range ;
19
19
use crate :: slice:: { self , SliceIndex } ;
20
+ use crate :: ub_checks:: assert_unsafe_precondition;
20
21
use crate :: { ascii, mem} ;
21
22
22
23
pub mod pattern;
@@ -720,7 +721,7 @@ impl str {
720
721
// is_char_boundary checks that the index is in [0, .len()]
721
722
if self . is_char_boundary ( mid) {
722
723
// 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) } )
724
725
} else {
725
726
None
726
727
}
@@ -766,15 +767,51 @@ impl str {
766
767
}
767
768
}
768
769
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.
770
798
///
771
799
/// # Safety
772
800
///
773
801
/// The caller must ensure that `mid` is a valid byte offset from the start
774
802
/// 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 ) {
776
806
let len = self . len ( ) ;
777
807
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
+
778
815
// SAFETY: caller guarantees `mid` is on a char boundary.
779
816
unsafe {
780
817
(
0 commit comments