Skip to content

str: Implement Container for ~str, @str and Mutable for ~str #7932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion src/libstd/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use cast;
use char;
use char::Char;
use clone::Clone;
use container::Container;
use container::{Container, Mutable};
use iter::Times;
use iterator::{Iterator, IteratorUtil, FilterIterator, AdditiveIterator, MapIterator};
use libc;
Expand Down Expand Up @@ -1211,6 +1211,31 @@ impl<'self> Container for &'self str {
}
}

impl Container for ~str {
#[inline]
fn len(&self) -> uint { self.as_slice().len() }
#[inline]
fn is_empty(&self) -> bool { self.len() == 0 }
}

impl Container for @str {
#[inline]
fn len(&self) -> uint { self.as_slice().len() }
#[inline]
fn is_empty(&self) -> bool { self.len() == 0 }
}

impl Mutable for ~str {
/// Remove all content, make the string empty
#[inline]
fn clear(&mut self) {
unsafe {
raw::set_len(self, 0)
}
}
}


#[allow(missing_doc)]
pub trait StrSlice<'self> {
fn contains<'a>(&self, needle: &'a str) -> bool;
Expand Down Expand Up @@ -2495,6 +2520,18 @@ mod tests {
assert_eq!(~"华ประเทศไทย中", data);
}

#[test]
fn test_clear() {
let mut empty = ~"";
empty.clear();
assert_eq!("", empty.as_slice());
let mut data = ~"ประเทศไทย中";
data.clear();
assert_eq!("", data.as_slice());
data.push_char('华');
assert_eq!("华", data.as_slice());
}

#[test]
fn test_split_within() {
fn t(s: &str, i: uint, u: &[~str]) {
Expand Down Expand Up @@ -3487,4 +3524,17 @@ mod tests {
t::<@str>();
t::<~str>();
}

#[test]
fn test_str_container() {
fn sum_len<S: Container>(v: &[S]) -> uint {
v.iter().transform(|x| x.len()).sum()
}

let s = ~"01234";
assert_eq!(5, sum_len(["012", "", "34"]));
assert_eq!(5, sum_len([@"01", @"2", @"34", @""]));
assert_eq!(5, sum_len([~"01", ~"2", ~"34", ~""]));
assert_eq!(5, sum_len([s.as_slice()]));
}
}