diff options
| author | Murarth <murarth@gmail.com> | 2016-07-11 15:06:28 -0700 |
|---|---|---|
| committer | Murarth <murarth@gmail.com> | 2016-07-11 18:07:14 -0700 |
| commit | 0bcf64cfc792c39b09d0626649c3d0c18257499a (patch) | |
| tree | 2660463eef7184e18b48711d264fae4890b18881 | |
| parent | 3ab8054ac182fc170099135304a0c1c6760da57a (diff) | |
| download | rust-0bcf64cfc792c39b09d0626649c3d0c18257499a.tar.gz rust-0bcf64cfc792c39b09d0626649c3d0c18257499a.zip | |
Add method `String::insert_str`
| -rw-r--r-- | src/libcollections/string.rs | 62 |
1 files changed, 53 insertions, 9 deletions
diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index eedf4c2c11f..ce3f9689324 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -1126,18 +1126,62 @@ impl String { assert!(idx <= len); assert!(self.is_char_boundary(idx)); let bits = ch.encode_utf8(); - let bits = bits.as_slice(); - let amt = bits.len(); + + unsafe { + self.insert_bytes(idx, bits.as_slice()); + } + } + + unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) { + let len = self.len(); + let amt = bytes.len(); self.vec.reserve(amt); + ptr::copy(self.vec.as_ptr().offset(idx as isize), + self.vec.as_mut_ptr().offset((idx + amt) as isize), + len - idx); + ptr::copy(bytes.as_ptr(), + self.vec.as_mut_ptr().offset(idx as isize), + amt); + self.vec.set_len(len + amt); + } + + /// Inserts a string into this `String` at a byte position. + /// + /// This is an `O(n)` operation as it requires copying every element in the + /// buffer. + /// + /// # Panics + /// + /// Panics if `idx` is larger than the `String`'s length, or if it does not + /// lie on a [`char`] boundary. + /// + /// [`char`]: ../../std/primitive.char.html + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(insert_str)] + /// + /// let mut s = String::from("bar"); + /// + /// s.insert_str(0, "foo"); + /// + /// assert_eq!("foobar", s); + /// ``` + #[inline] + #[unstable(feature = "insert_str", + reason = "recent addition", + issue = "0")] + pub fn insert_str(&mut self, idx: usize, string: &str) { + let len = self.len(); + assert!(idx <= len); + assert!(self.is_char_boundary(idx)); + unsafe { - ptr::copy(self.vec.as_ptr().offset(idx as isize), - self.vec.as_mut_ptr().offset((idx + amt) as isize), - len - idx); - ptr::copy(bits.as_ptr(), - self.vec.as_mut_ptr().offset(idx as isize), - amt); - self.vec.set_len(len + amt); + self.insert_bytes(idx, string.as_bytes()); } } |
