@@ -1726,8 +1726,9 @@ impl String {
1726
1726
let ch_len = ch. len_utf8 ( ) ;
1727
1727
self . reserve ( ch_len) ;
1728
1728
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.
1731
1732
unsafe {
1732
1733
ptr:: copy (
1733
1734
self . vec . as_ptr ( ) . add ( idx) ,
@@ -1736,13 +1737,13 @@ impl String {
1736
1737
) ;
1737
1738
}
1738
1739
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.
1741
1742
unsafe {
1742
1743
core:: char:: encode_utf8_raw_unchecked ( ch as u32 , self . vec . as_mut_ptr ( ) . add ( idx) ) ;
1743
1744
}
1744
1745
1745
- // SAFETY: `ch_len` initialized bytes have been added.
1746
+ // SAFETY: Update the length to include the newly added bytes .
1746
1747
unsafe {
1747
1748
self . vec . set_len ( len + ch_len) ;
1748
1749
}
@@ -1778,9 +1779,26 @@ impl String {
1778
1779
let amt = string. len ( ) ;
1779
1780
self . reserve ( amt) ;
1780
1781
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.
1781
1796
unsafe {
1782
- ptr:: copy ( self . vec . as_ptr ( ) . add ( idx) , self . vec . as_mut_ptr ( ) . add ( idx + amt) , len - idx) ;
1783
1797
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 {
1784
1802
self . vec . set_len ( len + amt) ;
1785
1803
}
1786
1804
}
0 commit comments