Skip to content

Commit

Permalink
Implemented FromIterator for std::hashmap
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkJr94 committed Jul 14, 2013
1 parent 8d0feb5 commit 4ff7ef4
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/libstd/hashmap.rs
Expand Up @@ -18,7 +18,7 @@
use container::{Container, Mutable, Map, Set};
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;
Expand Down Expand Up @@ -610,6 +610,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`
Expand Down Expand Up @@ -935,6 +947,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)]
Expand Down

0 comments on commit 4ff7ef4

Please sign in to comment.