@@ -2514,6 +2514,16 @@ pub trait OwnedStr {
2514
2514
/// Prepend a char to a string
2515
2515
fn unshift_char( & mut self , ch: char ) ;
2516
2516
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
+
2517
2527
/// Concatenate two strings together.
2518
2528
fn append( self , rhs: & str ) -> ~str ;
2519
2529
@@ -2626,6 +2636,24 @@ impl OwnedStr for ~str {
2626
2636
* self = new_str;
2627
2637
}
2628
2638
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
+
2629
2657
#[ inline]
2630
2658
fn append( self , rhs: & str ) -> ~str {
2631
2659
let mut new_str = self ;
@@ -2878,6 +2906,20 @@ mod tests {
2878
2906
assert_eq!(~" 华ประเทศไทย中", data);
2879
2907
}
2880
2908
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
+
2881
2923
#[test]
2882
2924
fn test_collect() {
2883
2925
let empty = ~" ";
0 commit comments