about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorSimon Sapin <simon.sapin@exyr.org>2013-12-05 15:19:44 +0000
committerSimon Sapin <simon.sapin@exyr.org>2013-12-31 11:20:40 +0100
commit80d0f60d29dfb24dcb5483ae3e7d7cf10b5264d2 (patch)
treed41fc9008b4e87911502445cc59622f85a361b08 /src/libstd
parentb88138a3ec4bb142fa514a863b62f955bf1c44e3 (diff)
downloadrust-80d0f60d29dfb24dcb5483ae3e7d7cf10b5264d2.tar.gz
rust-80d0f60d29dfb24dcb5483ae3e7d7cf10b5264d2.zip
Add .insert() and .insert_char() methods to ~str.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/str.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/libstd/str.rs b/src/libstd/str.rs
index 8e6d8523f77..c8a6fc08a38 100644
--- a/src/libstd/str.rs
+++ b/src/libstd/str.rs
@@ -2510,6 +2510,16 @@ pub trait OwnedStr {
     /// Prepend a char to a string
     fn unshift_char(&mut self, ch: char);
 
+    /// Insert a new sub-string at the given position in a string, in O(n + m) time
+    /// (with n and m the lengths of the string and the substring.)
+    /// This fails if `position` is not at a character boundary.
+    fn insert(&mut self, position: uint, substring: &str);
+
+    /// Insert a char at the given position in a string, in O(n + m) time
+    /// (with n and m the lengths of the string and the substring.)
+    /// This fails if `position` is not at a character boundary.
+    fn insert_char(&mut self, position: uint, ch: char);
+
     /// Concatenate two strings together.
     fn append(self, rhs: &str) -> ~str;
 
@@ -2623,6 +2633,24 @@ impl OwnedStr for ~str {
     }
 
     #[inline]
+    fn insert(&mut self, position: uint, substring: &str) {
+        // This could be more efficient.
+        let mut new_str = self.slice_to(position).to_owned();
+        new_str.push_str(substring);
+        new_str.push_str(self.slice_from(position));
+        *self = new_str;
+    }
+
+    #[inline]
+    fn insert_char(&mut self, position: uint, ch: char) {
+        // This could be more efficient.
+        let mut new_str = self.slice_to(position).to_owned();
+        new_str.push_char(ch);
+        new_str.push_str(self.slice_from(position));
+        *self = new_str;
+    }
+
+    #[inline]
     fn append(self, rhs: &str) -> ~str {
         let mut new_str = self;
         new_str.push_str_no_overallocate(rhs);
@@ -2875,6 +2903,20 @@ mod tests {
     }
 
     #[test]
+    fn test_insert_char() {
+        let mut data = ~"ประเทศไทย中";
+        data.insert_char(15, '华');
+        assert_eq!(~"ประเท华ศไทย中", data);
+    }
+
+    #[test]
+    fn test_insert() {
+        let mut data = ~"ประเทศไทย中";
+        data.insert(15, "华中");
+        assert_eq!(~"ประเท华中ศไทย中", data);
+    }
+
+    #[test]
     fn test_collect() {
         let empty = ~"";
         let s: ~str = empty.chars().collect();