Skip to content

Commit 7469914

Browse files
committed
Add str::split_at_mut
1 parent f900551 commit 7469914

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

src/libcollections/str.rs

+6
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,12 @@ impl str {
793793
core_str::StrExt::split_at(self, mid)
794794
}
795795

796+
/// Divide one mutable string slice into two at an index.
797+
#[inline]
798+
pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
799+
core_str::StrExt::split_at_mut(self, mid)
800+
}
801+
796802
/// An iterator over the codepoints of `self`.
797803
///
798804
/// # Examples

src/libcollectionstest/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
#![feature(ascii)]
1112
#![feature(append)]
1213
#![feature(bitset)]
1314
#![feature(bitvec)]

src/libcollectionstest/str.rs

+12
Original file line numberDiff line numberDiff line change
@@ -701,6 +701,18 @@ fn test_split_at() {
701701
assert_eq!(b, "");
702702
}
703703

704+
#[test]
705+
fn test_split_at_mut() {
706+
use std::ascii::AsciiExt;
707+
let mut s = "Hello World".to_string();
708+
{
709+
let (a, b) = s.split_at_mut(5);
710+
a.make_ascii_uppercase();
711+
b.make_ascii_lowercase();
712+
}
713+
assert_eq!(s, "HELLO world");
714+
}
715+
704716
#[test]
705717
#[should_panic]
706718
fn test_split_at_boundscheck() {

src/libcore/str/mod.rs

+15
Original file line numberDiff line numberDiff line change
@@ -1279,6 +1279,7 @@ pub trait StrExt {
12791279
where P::Searcher: ReverseSearcher<'a>;
12801280
fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>;
12811281
fn split_at(&self, mid: usize) -> (&str, &str);
1282+
fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
12821283
fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>;
12831284
fn subslice_offset(&self, inner: &str) -> usize;
12841285
fn as_ptr(&self) -> *const u8;
@@ -1591,6 +1592,20 @@ impl StrExt for str {
15911592
}
15921593
}
15931594

1595+
fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
1596+
// is_char_boundary checks that the index is in [0, .len()]
1597+
if self.is_char_boundary(mid) {
1598+
let len = self.len();
1599+
unsafe {
1600+
let self2: &mut str = mem::transmute_copy(&self);
1601+
(self.slice_mut_unchecked(0, mid),
1602+
self2.slice_mut_unchecked(mid, len))
1603+
}
1604+
} else {
1605+
slice_error_fail(self, 0, mid)
1606+
}
1607+
}
1608+
15941609
#[inline]
15951610
fn slice_shift_char(&self) -> Option<(char, &str)> {
15961611
if self.is_empty() {

0 commit comments

Comments
 (0)