Skip to content

Extend<&str> and FromIterator<&str> for String #19626

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

Merged
merged 4 commits into from
Dec 9, 2014
Merged
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
44 changes: 44 additions & 0 deletions src/libcollections/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -729,15 +729,38 @@ impl FromIterator<char> for String {
}
}

#[experimental = "waiting on FromIterator stabilization"]
impl<'a> FromIterator<&'a str> for String {
fn from_iter<I:Iterator<&'a str>>(iterator: I) -> String {
let mut buf = String::new();
buf.extend(iterator);
buf
}
}

#[experimental = "waiting on Extend stabilization"]
impl Extend<char> for String {
fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for ch in iterator {
self.push(ch)
}
}
}

#[experimental = "waiting on Extend stabilization"]
impl<'a> Extend<&'a str> for String {
fn extend<I: Iterator<&'a str>>(&mut self, mut iterator: I) {
// A guess that at least one byte per iterator element will be needed.
let (lower_bound, _) = iterator.size_hint();
self.reserve(lower_bound);
for s in iterator {
self.push_str(s)
}
}
}

impl PartialEq for String {
#[inline]
fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
Expand Down Expand Up @@ -1307,6 +1330,27 @@ mod tests {
"[[], [1], [1, 1]]".to_string());
}

#[test]
fn test_from_iterator() {
let s = "ศไทย中华Việt Nam".to_string();
let t = "ศไทย中华";
let u = "Việt Nam";

let a: String = s.chars().collect();
assert_eq!(s, a);

let mut b = t.to_string();
b.extend(u.chars());
assert_eq!(s, b);

let c: String = vec![t, u].into_iter().collect();
assert_eq!(s, c);

let mut d = t.to_string();
d.extend(vec![u].into_iter());
assert_eq!(s, d);
}

#[bench]
fn bench_with_capacity(b: &mut Bencher) {
b.iter(|| {
Expand Down