@@ -1132,18 +1132,62 @@ impl String {
1132
1132
assert ! ( idx <= len) ;
1133
1133
assert ! ( self . is_char_boundary( idx) ) ;
1134
1134
let bits = ch. encode_utf8 ( ) ;
1135
- let bits = bits. as_slice ( ) ;
1136
- let amt = bits. len ( ) ;
1135
+
1136
+ unsafe {
1137
+ self . insert_bytes ( idx, bits. as_slice ( ) ) ;
1138
+ }
1139
+ }
1140
+
1141
+ unsafe fn insert_bytes ( & mut self , idx : usize , bytes : & [ u8 ] ) {
1142
+ let len = self . len ( ) ;
1143
+ let amt = bytes. len ( ) ;
1137
1144
self . vec . reserve ( amt) ;
1138
1145
1146
+ ptr:: copy ( self . vec . as_ptr ( ) . offset ( idx as isize ) ,
1147
+ self . vec . as_mut_ptr ( ) . offset ( ( idx + amt) as isize ) ,
1148
+ len - idx) ;
1149
+ ptr:: copy ( bytes. as_ptr ( ) ,
1150
+ self . vec . as_mut_ptr ( ) . offset ( idx as isize ) ,
1151
+ amt) ;
1152
+ self . vec . set_len ( len + amt) ;
1153
+ }
1154
+
1155
+ /// Inserts a string into this `String` at a byte position.
1156
+ ///
1157
+ /// This is an `O(n)` operation as it requires copying every element in the
1158
+ /// buffer.
1159
+ ///
1160
+ /// # Panics
1161
+ ///
1162
+ /// Panics if `idx` is larger than the `String`'s length, or if it does not
1163
+ /// lie on a [`char`] boundary.
1164
+ ///
1165
+ /// [`char`]: ../../std/primitive.char.html
1166
+ ///
1167
+ /// # Examples
1168
+ ///
1169
+ /// Basic usage:
1170
+ ///
1171
+ /// ```
1172
+ /// #![feature(insert_str)]
1173
+ ///
1174
+ /// let mut s = String::from("bar");
1175
+ ///
1176
+ /// s.insert_str(0, "foo");
1177
+ ///
1178
+ /// assert_eq!("foobar", s);
1179
+ /// ```
1180
+ #[ inline]
1181
+ #[ unstable( feature = "insert_str" ,
1182
+ reason = "recent addition" ,
1183
+ issue = "0" ) ]
1184
+ pub fn insert_str ( & mut self , idx : usize , string : & str ) {
1185
+ let len = self . len ( ) ;
1186
+ assert ! ( idx <= len) ;
1187
+ assert ! ( self . is_char_boundary( idx) ) ;
1188
+
1139
1189
unsafe {
1140
- ptr:: copy ( self . vec . as_ptr ( ) . offset ( idx as isize ) ,
1141
- self . vec . as_mut_ptr ( ) . offset ( ( idx + amt) as isize ) ,
1142
- len - idx) ;
1143
- ptr:: copy ( bits. as_ptr ( ) ,
1144
- self . vec . as_mut_ptr ( ) . offset ( idx as isize ) ,
1145
- amt) ;
1146
- self . vec . set_len ( len + amt) ;
1190
+ self . insert_bytes ( idx, string. as_bytes ( ) ) ;
1147
1191
}
1148
1192
}
1149
1193
0 commit comments