about summary refs log tree commit diff
path: root/src/libstd/hashmap.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/libstd/hashmap.rs')
-rw-r--r--src/libstd/hashmap.rs50
1 files changed, 49 insertions, 1 deletions
diff --git a/src/libstd/hashmap.rs b/src/libstd/hashmap.rs
index e95c63e8912..0e31e47d56b 100644
--- a/src/libstd/hashmap.rs
+++ b/src/libstd/hashmap.rs
@@ -18,7 +18,7 @@
 use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
 use cmp::{Eq, Equiv};
 use hash::Hash;
-use iterator::{Iterator, IteratorUtil};
+use iterator::{Iterator, IteratorUtil, FromIterator};
 use num;
 use option::{None, Option, Some};
 use rand::RngUtil;
@@ -612,6 +612,18 @@ impl<'self, K> Iterator<&'self K> for HashSetIterator<'self, K> {
     }
 }
 
+impl<K: Eq + Hash, V, T: Iterator<(K, V)>> FromIterator<(K, V), T> for HashMap<K, V> {
+    pub fn from_iterator(iter: &mut T) -> HashMap<K, V> {
+        let (lower, _) = iter.size_hint();
+        let mut map = HashMap::with_capacity(lower);
+
+        for iter.advance |(k, v)| {
+            map.insert(k, v);
+        }
+
+        map
+    }
+}
 
 /// An implementation of a hash set using the underlying representation of a
 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
@@ -727,6 +739,20 @@ impl<T:Hash + Eq> HashSet<T> {
     }
 }
 
+impl<K: Eq + Hash, T: Iterator<K>> FromIterator<K, T> for HashSet<K> {
+    pub fn from_iterator(iter: &mut T) -> HashSet<K> {
+        let (lower, _) = iter.size_hint();
+        let mut set = HashSet::with_capacity(lower);
+
+        for iter.advance |k| {
+            set.insert(k);
+        }
+
+        set
+    }
+}
+
+
 #[cfg(test)]
 mod test_map {
     use container::{Container, Map, Set};
@@ -939,6 +965,17 @@ mod test_map {
 
         assert_eq!(m.find_equiv(&("qux")), None);
     }
+
+    #[test]
+    fn test_from_iter() {
+        let xs = ~[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
+
+        let map: HashMap<int, int> = xs.iter().transform(|&x| x).collect();
+
+        for xs.iter().advance |&(k, v)| {
+            assert_eq!(map.find(&k), Some(&v));
+        }
+    }
 }
 
 #[cfg(test)]
@@ -1120,4 +1157,15 @@ mod test_set {
         }
         assert_eq!(i, expected.len());
     }
+
+    #[test]
+    fn test_from_iter() {
+        let xs = ~[1, 2, 3, 4, 5, 6, 7, 8, 9];
+
+        let set: HashSet<int> = xs.iter().transform(|&x| x).collect();
+
+        for xs.iter().advance |x: &int| {
+            assert!(set.contains(x));
+        }
+    }
 }