about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorblake2-ppc <blake2-ppc>2013-07-29 02:40:28 +0200
committerblake2-ppc <blake2-ppc>2013-07-29 02:40:28 +0200
commit4849a42bf6dc2db72797d3c0a8a197c69f4872be (patch)
tree70583c03af5aa3bea23f30c74c09f7e1a5e013f7 /src/libstd
parent4cc3bbb83d3e45cac17537514d08257e5a94cc61 (diff)
downloadrust-4849a42bf6dc2db72797d3c0a8a197c69f4872be.tar.gz
rust-4849a42bf6dc2db72797d3c0a8a197c69f4872be.zip
std: Implement FromIterator for ~str
FromIterator initially only implemented for Iterator<char>, which is the
type of the main iterator.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/str.rs24
1 files changed, 23 insertions, 1 deletions
diff --git a/src/libstd/str.rs b/src/libstd/str.rs
index cbd1e47b29b..c616689d966 100644
--- a/src/libstd/str.rs
+++ b/src/libstd/str.rs
@@ -23,7 +23,7 @@ use char::Char;
 use clone::Clone;
 use container::{Container, Mutable};
 use iter::Times;
-use iterator::{Iterator, IteratorUtil, FilterIterator, AdditiveIterator, MapIterator};
+use iterator::{Iterator, FromIterator, IteratorUtil, FilterIterator, AdditiveIterator, MapIterator};
 use libc;
 use num::Zero;
 use option::{None, Option, Some};
@@ -2319,6 +2319,18 @@ impl<'self> Iterator<u8> for BytesRevIterator<'self> {
     }
 }
 
+impl<T: Iterator<char>> FromIterator<char, T> for ~str {
+    #[inline]
+    fn from_iterator(iterator: &mut T) -> ~str {
+        let (lower, _) = iterator.size_hint();
+        let mut buf = with_capacity(lower);
+        for iterator.advance |ch| {
+            buf.push_char(ch)
+        }
+        buf
+    }
+}
+
 // This works because every lifetime is a sub-lifetime of 'static
 impl<'self> Zero for &'self str {
     fn zero() -> &'self str { "" }
@@ -2483,6 +2495,16 @@ mod tests {
     }
 
     #[test]
+    fn test_collect() {
+        let empty = "";
+        let s: ~str = empty.iter().collect();
+        assert_eq!(empty, s.as_slice());
+        let data = "ประเทศไทย中";
+        let s: ~str = data.iter().collect();
+        assert_eq!(data, s.as_slice());
+    }
+
+    #[test]
     fn test_clear() {
         let mut empty = ~"";
         empty.clear();