From: Simon Sapin Date: Mon, 15 Jun 2015 17:24:52 +0000 (+0200) Subject: Add str::split_at_mut X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=7469914e96a511487e8248d2f8a583befb02149f;p=rust.git Add str::split_at_mut --- diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 711e2887865..306a8ba3e09 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -793,6 +793,12 @@ pub fn split_at(&self, mid: usize) -> (&str, &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 diff --git a/src/libcollectionstest/lib.rs b/src/libcollectionstest/lib.rs index 6bf7380fdeb..233623b8a5e 100644 --- a/src/libcollectionstest/lib.rs +++ b/src/libcollectionstest/lib.rs @@ -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)] diff --git a/src/libcollectionstest/str.rs b/src/libcollectionstest/str.rs index 4eee99f2bc9..66d95697102 100644 --- a/src/libcollectionstest/str.rs +++ b/src/libcollectionstest/str.rs @@ -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() { diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index c8237720b0e..7e4c2ba3be8 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1279,6 +1279,7 @@ fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option where P::Searcher: ReverseSearcher<'a>; fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option; 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; @@ -1591,6 +1592,20 @@ fn split_at(&self, mid: usize) -> (&str, &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() {