rollup merge of #19626: bluss/string-extend-str

Strings iterate to both char and &str, so it is natural it can also be extended or collected from an iterator of &str.

Apart from the trait implementations, `Extend<char>` is updated to use the iterator size hint, and the test added tests both the char and the &str versions of Extend and FromIterator.
This commit is contained in:
Alex Crichton 2014-12-09 09:25:10 -08:00
commit 4b34f3c3ad

View File

@ -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) }
@ -1307,6 +1330,27 @@ mod tests {
"[[], [1], [1, 1]]");
}
#[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(|| {