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