@@ -22,7 +22,7 @@ use cast;
22
22
use char;
23
23
use char:: Char ;
24
24
use clone:: Clone ;
25
- use container:: Container ;
25
+ use container:: { Container , Mutable } ;
26
26
use iter:: Times ;
27
27
use iterator:: { Iterator , IteratorUtil , FilterIterator , AdditiveIterator , MapIterator } ;
28
28
use libc;
@@ -1214,6 +1214,31 @@ impl<'self> Container for &'self str {
1214
1214
}
1215
1215
}
1216
1216
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
+
1217
1242
#[allow(missing_doc)]
1218
1243
pub trait StrSlice<'self> {
1219
1244
fn contains<'a>(&self, needle: &'a str) -> bool;
@@ -2502,6 +2527,18 @@ mod tests {
2502
2527
assert_eq!(~" 华ประเทศไทย中", data);
2503
2528
}
2504
2529
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
+
2505
2542
#[test]
2506
2543
fn test_split_within() {
2507
2544
fn t(s: &str, i: uint, u: &[~str]) {
@@ -3494,4 +3531,17 @@ mod tests {
3494
3531
t:: <@str >( ) ;
3495
3532
t:: <~str >( ) ;
3496
3533
}
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
+ }
3497
3547
}
0 commit comments