@@ -2510,6 +2510,16 @@ pub trait OwnedStr {
2510
2510
/// Prepend a char to a string
2511
2511
fn unshift_char( & mut self , ch: char ) ;
2512
2512
2513
+ /// Insert a new sub-string at the given position in a string, in O(n + m) time
2514
+ /// (with n and m the lengths of the string and the substring.)
2515
+ /// This fails if `position` is not at a character boundary.
2516
+ fn insert( & mut self , position: uint, substring: & str ) ;
2517
+
2518
+ /// Insert a char at the given position in a string, in O(n + m) time
2519
+ /// (with n and m the lengths of the string and the substring.)
2520
+ /// This fails if `position` is not at a character boundary.
2521
+ fn insert_char( & mut self , position: uint, ch: char ) ;
2522
+
2513
2523
/// Concatenate two strings together.
2514
2524
fn append( self , rhs: & str ) -> ~str ;
2515
2525
@@ -2622,6 +2632,24 @@ impl OwnedStr for ~str {
2622
2632
* self = new_str;
2623
2633
}
2624
2634
2635
+ #[ inline]
2636
+ fn insert( & mut self , position: uint, substring: & str ) {
2637
+ // This could be more efficient.
2638
+ let mut new_str = self . slice_to( position) . to_owned( ) ;
2639
+ new_str. push_str( substring) ;
2640
+ new_str. push_str( self . slice_from( position) ) ;
2641
+ * self = new_str;
2642
+ }
2643
+
2644
+ #[ inline]
2645
+ fn insert_char( & mut self , position: uint, ch: char ) {
2646
+ // This could be more efficient.
2647
+ let mut new_str = self . slice_to( position) . to_owned( ) ;
2648
+ new_str. push_char( ch) ;
2649
+ new_str. push_str( self . slice_from( position) ) ;
2650
+ * self = new_str;
2651
+ }
2652
+
2625
2653
#[ inline]
2626
2654
fn append( self , rhs: & str ) -> ~str {
2627
2655
let mut new_str = self ;
@@ -2874,6 +2902,20 @@ mod tests {
2874
2902
assert_eq!(~" 华ประเทศไทย中", data);
2875
2903
}
2876
2904
2905
+ #[test]
2906
+ fn test_insert_char() {
2907
+ let mut data = ~" ประเทศไทย中";
2908
+ data.insert_char(15, '华');
2909
+ assert_eq!(~" ประเท华ศไทย中", data);
2910
+ }
2911
+
2912
+ #[test]
2913
+ fn test_insert() {
2914
+ let mut data = ~" ประเทศไทย中";
2915
+ data.insert(15, " 华中");
2916
+ assert_eq!(~" ประเท华中ศไทย中", data);
2917
+ }
2918
+
2877
2919
#[test]
2878
2920
fn test_collect() {
2879
2921
let empty = ~" ";
0 commit comments