@@ -2514,6 +2514,16 @@ pub trait OwnedStr {
25142514 /// Prepend a char to a string
25152515 fn unshift_char( & mut self , ch: char ) ;
25162516
2517+ /// Insert a new sub-string at the given position in a string, in O(n + m) time
2518+ /// (with n and m the lengths of the string and the substring.)
2519+ /// This fails if `position` is not at a character boundary.
2520+ fn insert( & mut self , position: uint, substring: & str ) ;
2521+
2522+ /// Insert a char at the given position in a string, in O(n + m) time
2523+ /// (with n and m the lengths of the string and the substring.)
2524+ /// This fails if `position` is not at a character boundary.
2525+ fn insert_char( & mut self , position: uint, ch: char ) ;
2526+
25172527 /// Concatenate two strings together.
25182528 fn append( self , rhs: & str ) -> ~str ;
25192529
@@ -2626,6 +2636,24 @@ impl OwnedStr for ~str {
26262636 * self = new_str;
26272637 }
26282638
2639+ #[ inline]
2640+ fn insert( & mut self , position: uint, substring: & str ) {
2641+ // This could be more efficient.
2642+ let mut new_str = self . slice_to( position) . to_owned( ) ;
2643+ new_str. push_str( substring) ;
2644+ new_str. push_str( self . slice_from( position) ) ;
2645+ * self = new_str;
2646+ }
2647+
2648+ #[ inline]
2649+ fn insert_char( & mut self , position: uint, ch: char ) {
2650+ // This could be more efficient.
2651+ let mut new_str = self . slice_to( position) . to_owned( ) ;
2652+ new_str. push_char( ch) ;
2653+ new_str. push_str( self . slice_from( position) ) ;
2654+ * self = new_str;
2655+ }
2656+
26292657 #[ inline]
26302658 fn append( self , rhs: & str ) -> ~str {
26312659 let mut new_str = self ;
@@ -2878,6 +2906,20 @@ mod tests {
28782906 assert_eq!(~" 华ประเทศไทย中", data);
28792907 }
28802908
2909+ #[test]
2910+ fn test_insert_char() {
2911+ let mut data = ~" ประเทศไทย中";
2912+ data.insert_char(15, '华');
2913+ assert_eq!(~" ประเท华ศไทย中", data);
2914+ }
2915+
2916+ #[test]
2917+ fn test_insert() {
2918+ let mut data = ~" ประเทศไทย中";
2919+ data.insert(15, " 华中");
2920+ assert_eq!(~" ประเท华中ศไทย中", data);
2921+ }
2922+
28812923 #[test]
28822924 fn test_collect() {
28832925 let empty = ~" ";
0 commit comments