Skip to content

Commit 4ff7ef4

Browse files
committed
Implemented FromIterator for std::hashmap
1 parent 8d0feb5 commit 4ff7ef4

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/libstd/hashmap.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
use container::{Container, Mutable, Map, Set};
1919
use cmp::{Eq, Equiv};
2020
use hash::Hash;
21-
use iterator::{Iterator, IteratorUtil};
21+
use iterator::{Iterator, IteratorUtil, FromIterator};
2222
use num;
2323
use option::{None, Option, Some};
2424
use rand::RngUtil;
@@ -610,6 +610,18 @@ impl<'self, K> Iterator<&'self K> for HashSetIterator<'self, K> {
610610
}
611611
}
612612

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+
}
613625

614626
/// An implementation of a hash set using the underlying representation of a
615627
/// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
@@ -935,6 +947,17 @@ mod test_map {
935947

936948
assert_eq!(m.find_equiv(&("qux")), None);
937949
}
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+
}
938961
}
939962

940963
#[cfg(test)]

0 commit comments

Comments
 (0)