Skip to content

Commit 4b34f3c

Browse files
committed
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.
2 parents 1cbb075 + a813469 commit 4b34f3c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/libcollections/string.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,15 +729,38 @@ impl FromIterator<char> for String {
729729
}
730730
}
731731

732+
#[experimental = "waiting on FromIterator stabilization"]
733+
impl<'a> FromIterator<&'a str> for String {
734+
fn from_iter<I:Iterator<&'a str>>(iterator: I) -> String {
735+
let mut buf = String::new();
736+
buf.extend(iterator);
737+
buf
738+
}
739+
}
740+
732741
#[experimental = "waiting on Extend stabilization"]
733742
impl Extend<char> for String {
734743
fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
744+
let (lower_bound, _) = iterator.size_hint();
745+
self.reserve(lower_bound);
735746
for ch in iterator {
736747
self.push(ch)
737748
}
738749
}
739750
}
740751

752+
#[experimental = "waiting on Extend stabilization"]
753+
impl<'a> Extend<&'a str> for String {
754+
fn extend<I: Iterator<&'a str>>(&mut self, mut iterator: I) {
755+
// A guess that at least one byte per iterator element will be needed.
756+
let (lower_bound, _) = iterator.size_hint();
757+
self.reserve(lower_bound);
758+
for s in iterator {
759+
self.push_str(s)
760+
}
761+
}
762+
}
763+
741764
impl PartialEq for String {
742765
#[inline]
743766
fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
@@ -1307,6 +1330,27 @@ mod tests {
13071330
"[[], [1], [1, 1]]");
13081331
}
13091332

1333+
#[test]
1334+
fn test_from_iterator() {
1335+
let s = "ศไทย中华Việt Nam".to_string();
1336+
let t = "ศไทย中华";
1337+
let u = "Việt Nam";
1338+
1339+
let a: String = s.chars().collect();
1340+
assert_eq!(s, a);
1341+
1342+
let mut b = t.to_string();
1343+
b.extend(u.chars());
1344+
assert_eq!(s, b);
1345+
1346+
let c: String = vec![t, u].into_iter().collect();
1347+
assert_eq!(s, c);
1348+
1349+
let mut d = t.to_string();
1350+
d.extend(vec![u].into_iter());
1351+
assert_eq!(s, d);
1352+
}
1353+
13101354
#[bench]
13111355
fn bench_with_capacity(b: &mut Bencher) {
13121356
b.iter(|| {

0 commit comments

Comments
 (0)