Skip to content

Commit

Permalink
Add str::split_at_mut
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSapin committed Jul 13, 2015
1 parent f900551 commit 7469914
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/libcollections/str.rs
Expand Up @@ -793,6 +793,12 @@ impl str {
core_str::StrExt::split_at(self, mid)
}

/// Divide one mutable string slice into two at an index.
#[inline]
pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
core_str::StrExt::split_at_mut(self, mid)
}

/// An iterator over the codepoints of `self`.
///
/// # Examples
Expand Down
1 change: 1 addition & 0 deletions src/libcollectionstest/lib.rs
Expand Up @@ -8,6 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(ascii)]
#![feature(append)]
#![feature(bitset)]
#![feature(bitvec)]
Expand Down
12 changes: 12 additions & 0 deletions src/libcollectionstest/str.rs
Expand Up @@ -701,6 +701,18 @@ fn test_split_at() {
assert_eq!(b, "");
}

#[test]
fn test_split_at_mut() {
use std::ascii::AsciiExt;
let mut s = "Hello World".to_string();
{
let (a, b) = s.split_at_mut(5);
a.make_ascii_uppercase();
b.make_ascii_lowercase();
}
assert_eq!(s, "HELLO world");
}

#[test]
#[should_panic]
fn test_split_at_boundscheck() {
Expand Down
15 changes: 15 additions & 0 deletions src/libcore/str/mod.rs
Expand Up @@ -1279,6 +1279,7 @@ pub trait StrExt {
where P::Searcher: ReverseSearcher<'a>;
fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
fn split_at(&self, mid: usize) -> (&str, &str);
fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
fn subslice_offset(&self, inner: &str) -> usize;
fn as_ptr(&self) -> *const u8;
Expand Down Expand Up @@ -1591,6 +1592,20 @@ impl StrExt for str {
}
}

fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
// is_char_boundary checks that the index is in [0, .len()]
if self.is_char_boundary(mid) {
let len = self.len();
unsafe {
let self2: &mut str = mem::transmute_copy(&self);
(self.slice_mut_unchecked(0, mid),
self2.slice_mut_unchecked(mid, len))
}
} else {
slice_error_fail(self, 0, mid)
}
}

#[inline]
fn slice_shift_char(&self) -> Option<(char, &str)> {
if self.is_empty() {
Expand Down

0 comments on commit 7469914

Please sign in to comment.