@@ -716,26 +716,23 @@ impl<LenT: LenType, S: StringStorage + ?Sized> StringInner<LenT, S> {
716
716
717
717
// SAFETY: Move the bytes starting from `idx` to their new location `ch_len`
718
718
// bytes ahead. This is safe because we checked `len + ch_len` does not
719
- // exceed the capacity and `idx` is a char boundary
719
+ // exceed the capacity and `idx` is a char boundary.
720
720
unsafe {
721
721
let ptr = self . vec . as_mut_ptr ( ) ;
722
722
core:: ptr:: copy ( ptr. add ( idx) , ptr. add ( idx + ch_len) , len - idx) ;
723
723
}
724
724
725
- // SAFETY: Copy the encoded character into the vacated region if
726
- // `idx != len`, or into the uninitialized spare capacity otherwise.
725
+ // SAFETY: Encode the character into the vacated region if `idx != len`,
726
+ // or into the uninitialized spare capacity otherwise. This is safe
727
+ // because `is_char_boundary` checks that `idx <= len`, and we checked that
728
+ // `(idx + ch_len)` does not exceed the capacity.
727
729
unsafe {
728
- // 4 bytes is the maximum length of a UTF-8 character
729
- let mut buf = [ 0u8 ; 4 ] ;
730
- let encoded = ch. encode_utf8 ( & mut buf) ;
731
- core:: ptr:: copy_nonoverlapping (
732
- encoded. as_ptr ( ) ,
733
- self . vec . as_mut_ptr ( ) . add ( idx) ,
734
- ch_len,
735
- ) ;
730
+ let buf = core:: slice:: from_raw_parts_mut ( self . vec . as_mut_ptr ( ) . add ( idx) , ch_len) ;
731
+ ch. encode_utf8 ( buf) ;
736
732
}
737
733
738
- // SAFETY: Update the length to include the newly added bytes.
734
+ // SAFETY: Update the length to include the newly added bytes. This is
735
+ // safe because we checked that `len + ch_len` does not exceed the capacity.
739
736
unsafe {
740
737
self . vec . set_len ( len + ch_len) ;
741
738
}
0 commit comments