Skip to content

Commit 80d0f60

Browse files
committed
Add .insert() and .insert_char() methods to ~str.
1 parent b88138a commit 80d0f60

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/libstd/str.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2510,6 +2510,16 @@ pub trait OwnedStr {
25102510
/// Prepend a char to a string
25112511
fn unshift_char(&mut self, ch: char);
25122512

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+
25132523
/// Concatenate two strings together.
25142524
fn append(self, rhs: &str) -> ~str;
25152525

@@ -2622,6 +2632,24 @@ impl OwnedStr for ~str {
26222632
*self = new_str;
26232633
}
26242634

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+
26252653
#[inline]
26262654
fn append(self, rhs: &str) -> ~str {
26272655
let mut new_str = self;
@@ -2874,6 +2902,20 @@ mod tests {
28742902
assert_eq!(~"华ประเทศไทย中", data);
28752903
}
28762904
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+
28772919
#[test]
28782920
fn test_collect() {
28792921
let empty = ~"";

0 commit comments

Comments
 (0)