Skip to content

Commit 3509f9d

Browse files
author
blake2-ppc
committed
str: Implement Container for ~str, @str and Mutable for ~str
~str and @str need separate implementations for use in generic functions, where it will not automatically use the impl on &str.
1 parent e3142c5 commit 3509f9d

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;
@@ -1211,6 +1211,31 @@ impl<'self> Container for &'self str {
12111211
}
12121212
}
12131213
1214+
impl Container for ~str {
1215+
#[inline]
1216+
fn len(&self) -> uint { self.as_slice().len() }
1217+
#[inline]
1218+
fn is_empty(&self) -> bool { self.len() == 0 }
1219+
}
1220+
1221+
impl Container for @str {
1222+
#[inline]
1223+
fn len(&self) -> uint { self.as_slice().len() }
1224+
#[inline]
1225+
fn is_empty(&self) -> bool { self.len() == 0 }
1226+
}
1227+
1228+
impl Mutable for ~str {
1229+
/// Remove all content, make the string empty
1230+
#[inline]
1231+
fn clear(&mut self) {
1232+
unsafe {
1233+
raw::set_len(self, 0)
1234+
}
1235+
}
1236+
}
1237+
1238+
12141239
#[allow(missing_doc)]
12151240
pub trait StrSlice<'self> {
12161241
fn contains<'a>(&self, needle: &'a str) -> bool;
@@ -2495,6 +2520,18 @@ mod tests {
24952520
assert_eq!(~"华ประเทศไทย中", data);
24962521
}
24972522
2523+
#[test]
2524+
fn test_clear() {
2525+
let mut empty = ~"";
2526+
empty.clear();
2527+
assert_eq!("", empty.as_slice());
2528+
let mut data = ~"ประเทศไทย中";
2529+
data.clear();
2530+
assert_eq!("", data.as_slice());
2531+
data.push_char('华');
2532+
assert_eq!("", data.as_slice());
2533+
}
2534+
24982535
#[test]
24992536
fn test_split_within() {
25002537
fn t(s: &str, i: uint, u: &[~str]) {
@@ -3487,4 +3524,17 @@ mod tests {
34873524
t::<@str>();
34883525
t::<~str>();
34893526
}
3527+
3528+
#[test]
3529+
fn test_str_container() {
3530+
fn sum_len<S: Container>(v: &[S]) -> uint {
3531+
v.iter().transform(|x| x.len()).sum()
3532+
}
3533+
3534+
let s = ~"01234";
3535+
assert_eq!(5, sum_len(["012", "", "34"]));
3536+
assert_eq!(5, sum_len([@"01", @"2", @"34", @""]));
3537+
assert_eq!(5, sum_len([~"01", ~"2", ~"34", ~""]));
3538+
assert_eq!(5, sum_len([s.as_slice()]));
3539+
}
34903540
}

0 commit comments

Comments
 (0)