Skip to content

Commit fe3f75f

Browse files
committed
auto merge of #7932 : blake2-ppc/rust/str-clear, r=huonw
~str and @str need separate implementations for use in generic functions, where it will not automatically use the impl on &str. fixes issue #7900
2 parents e336cbf + 3509f9d commit fe3f75f

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

src/libstd/str.rs

+51-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use cast;
2222
use char;
2323
use char::Char;
2424
use clone::Clone;
25-
use container::Container;
25+
use container::{Container, Mutable};
2626
use iter::Times;
2727
use iterator::{Iterator, IteratorUtil, FilterIterator, AdditiveIterator, MapIterator};
2828
use libc;
@@ -1214,6 +1214,31 @@ impl<'self> Container for &'self str {
12141214
}
12151215
}
12161216
1217+
impl Container for ~str {
1218+
#[inline]
1219+
fn len(&self) -> uint { self.as_slice().len() }
1220+
#[inline]
1221+
fn is_empty(&self) -> bool { self.len() == 0 }
1222+
}
1223+
1224+
impl Container for @str {
1225+
#[inline]
1226+
fn len(&self) -> uint { self.as_slice().len() }
1227+
#[inline]
1228+
fn is_empty(&self) -> bool { self.len() == 0 }
1229+
}
1230+
1231+
impl Mutable for ~str {
1232+
/// Remove all content, make the string empty
1233+
#[inline]
1234+
fn clear(&mut self) {
1235+
unsafe {
1236+
raw::set_len(self, 0)
1237+
}
1238+
}
1239+
}
1240+
1241+
12171242
#[allow(missing_doc)]
12181243
pub trait StrSlice<'self> {
12191244
fn contains<'a>(&self, needle: &'a str) -> bool;
@@ -2502,6 +2527,18 @@ mod tests {
25022527
assert_eq!(~"华ประเทศไทย中", data);
25032528
}
25042529
2530+
#[test]
2531+
fn test_clear() {
2532+
let mut empty = ~"";
2533+
empty.clear();
2534+
assert_eq!("", empty.as_slice());
2535+
let mut data = ~"ประเทศไทย中";
2536+
data.clear();
2537+
assert_eq!("", data.as_slice());
2538+
data.push_char('华');
2539+
assert_eq!("", data.as_slice());
2540+
}
2541+
25052542
#[test]
25062543
fn test_split_within() {
25072544
fn t(s: &str, i: uint, u: &[~str]) {
@@ -3494,4 +3531,17 @@ mod tests {
34943531
t::<@str>();
34953532
t::<~str>();
34963533
}
3534+
3535+
#[test]
3536+
fn test_str_container() {
3537+
fn sum_len<S: Container>(v: &[S]) -> uint {
3538+
v.iter().transform(|x| x.len()).sum()
3539+
}
3540+
3541+
let s = ~"01234";
3542+
assert_eq!(5, sum_len(["012", "", "34"]));
3543+
assert_eq!(5, sum_len([@"01", @"2", @"34", @""]));
3544+
assert_eq!(5, sum_len([~"01", ~"2", ~"34", ~""]));
3545+
assert_eq!(5, sum_len([s.as_slice()]));
3546+
}
34973547
}

0 commit comments

Comments
 (0)