Skip to content

Commit 451a98b

Browse files
Update insert to encode directly into the destination buffer
1 parent 8247cf2 commit 451a98b

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

src/string/mod.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -716,26 +716,23 @@ impl<LenT: LenType, S: StringStorage + ?Sized> StringInner<LenT, S> {
716716

717717
// SAFETY: Move the bytes starting from `idx` to their new location `ch_len`
718718
// 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.
720720
unsafe {
721721
let ptr = self.vec.as_mut_ptr();
722722
core::ptr::copy(ptr.add(idx), ptr.add(idx + ch_len), len - idx);
723723
}
724724

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.
727729
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);
736732
}
737733

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.
739736
unsafe {
740737
self.vec.set_len(len + ch_len);
741738
}

0 commit comments

Comments
 (0)