@@ -1726,8 +1726,9 @@ impl String {
17261726 let ch_len = ch. len_utf8 ( ) ;
17271727 self . reserve ( ch_len) ;
17281728
1729- // SAFETY: Shift data `ch_len` bytes to the right,
1730- // capacity was just reserved for at least that many bytes.
1729+ // SAFETY: Move the bytes starting from `idx` to their new location `ch_len`
1730+ // bytes ahead. This is safe because sufficient capacity was reserved, and `idx`
1731+ // is a char boundary.
17311732 unsafe {
17321733 ptr:: copy (
17331734 self . vec . as_ptr ( ) . add ( idx) ,
@@ -1736,13 +1737,13 @@ impl String {
17361737 ) ;
17371738 }
17381739
1739- // SAFETY: Encode the character into the space left after the shift
1740- // if `idx != len`, or into the uninitialized spare capacity otherwise.
1740+ // SAFETY: Encode the character into the vacated region if `idx != len`,
1741+ // or into the uninitialized spare capacity otherwise.
17411742 unsafe {
17421743 core:: char:: encode_utf8_raw_unchecked ( ch as u32 , self . vec . as_mut_ptr ( ) . add ( idx) ) ;
17431744 }
17441745
1745- // SAFETY: `ch_len` initialized bytes have been added.
1746+ // SAFETY: Update the length to include the newly added bytes .
17461747 unsafe {
17471748 self . vec . set_len ( len + ch_len) ;
17481749 }
@@ -1778,9 +1779,26 @@ impl String {
17781779 let amt = string. len ( ) ;
17791780 self . reserve ( amt) ;
17801781
1782+ // SAFETY: Move the bytes starting from `idx` to their new location `amt` bytes
1783+ // ahead. This is safe because sufficient capacity was just reserved, and `idx`
1784+ // is a char boundary.
1785+ unsafe {
1786+ ptr:: copy (
1787+ self . vec . as_ptr ( ) . add ( idx) ,
1788+ self . vec . as_mut_ptr ( ) . add ( idx + amt) ,
1789+ len - idx,
1790+ ) ;
1791+ }
1792+
1793+ // SAFETY: Copy the new string slice into the vacated region if `idx != len`,
1794+ // or into the uninitialized spare capacity otherwise. The borrow checker
1795+ // ensures that the source and destination do not overlap.
17811796 unsafe {
1782- ptr:: copy ( self . vec . as_ptr ( ) . add ( idx) , self . vec . as_mut_ptr ( ) . add ( idx + amt) , len - idx) ;
17831797 ptr:: copy_nonoverlapping ( string. as_ptr ( ) , self . vec . as_mut_ptr ( ) . add ( idx) , amt) ;
1798+ }
1799+
1800+ // SAFETY: Update the length to include the newly added bytes.
1801+ unsafe {
17841802 self . vec . set_len ( len + amt) ;
17851803 }
17861804 }
0 commit comments