|
18 | 18 | use container::{Container, Mutable, Map, Set};
|
19 | 19 | use cmp::{Eq, Equiv};
|
20 | 20 | use hash::Hash;
|
21 |
| -use iterator::{Iterator, IteratorUtil}; |
| 21 | +use iterator::{Iterator, IteratorUtil, FromIterator}; |
22 | 22 | use num;
|
23 | 23 | use option::{None, Option, Some};
|
24 | 24 | use rand::RngUtil;
|
@@ -610,6 +610,18 @@ impl<'self, K> Iterator<&'self K> for HashSetIterator<'self, K> {
|
610 | 610 | }
|
611 | 611 | }
|
612 | 612 |
|
| 613 | +impl<K: Eq + Hash, V, T: Iterator<(K, V)>> FromIterator<(K, V), T> for HashMap<K, V> { |
| 614 | + pub fn from_iterator(iter: &mut T) -> HashMap<K, V> { |
| 615 | + let (lower, _) = iter.size_hint(); |
| 616 | + let mut map = HashMap::with_capacity(lower); |
| 617 | + |
| 618 | + for iter.advance |(k, v)| { |
| 619 | + map.insert(k, v); |
| 620 | + } |
| 621 | + |
| 622 | + map |
| 623 | + } |
| 624 | +} |
613 | 625 |
|
614 | 626 | /// An implementation of a hash set using the underlying representation of a
|
615 | 627 | /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
|
@@ -935,6 +947,17 @@ mod test_map {
|
935 | 947 |
|
936 | 948 | assert_eq!(m.find_equiv(&("qux")), None);
|
937 | 949 | }
|
| 950 | + |
| 951 | + #[test] |
| 952 | + fn test_from_iter() { |
| 953 | + let xs = ~[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; |
| 954 | + |
| 955 | + let map: HashMap<int, int> = xs.iter().transform(|&x| x).collect(); |
| 956 | + |
| 957 | + for xs.iter().advance |&(k, v)| { |
| 958 | + assert_eq!(map.find(&k), Some(&v)); |
| 959 | + } |
| 960 | + } |
938 | 961 | }
|
939 | 962 |
|
940 | 963 | #[cfg(test)]
|
|
0 commit comments