]> git.lizzy.rs Git - rust.git/commitdiff
string: Implement FromIterator<&str> and Extend<&str> for String
authorbluss <bluss>
Sun, 7 Dec 2014 20:32:00 +0000 (21:32 +0100)
committerbluss <bluss>
Sun, 7 Dec 2014 21:45:27 +0000 (22:45 +0100)
&str is a "particle" of a string already, see the graphemes iterator,
so it seems natural that we should be able to use it with Extend.

src/libcollections/string.rs

index 961fca0f02b9a159dbdf9f2ee7c1297ecf364914..ed578f3f515b65603c1e46f2b0832ad159fbfb19 100644 (file)
@@ -729,6 +729,15 @@ fn from_iter<I:Iterator<char>>(iterator: I) -> 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) {
@@ -740,6 +749,18 @@ fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
     }
 }
 
+#[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) }