From 67a1c3526435b06f7ed0f19828ff14f2e7b90a35 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Wed, 14 Mar 2012 19:32:19 -0700 Subject: std: Add a a hashmap_from_vecs function --- src/libstd/map.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/map.rs b/src/libstd/map.rs index 760dab76643..29d3579afa3 100644 --- a/src/libstd/map.rs +++ b/src/libstd/map.rs @@ -3,6 +3,8 @@ import chained::hashmap; export hashmap, hashfn, eqfn, set, map, chained, hashmap, str_hash; export bytes_hash, int_hash, uint_hash, set_add; +export hash_from_vec, hash_from_strs, hash_from_bytes; +export hash_from_ints, hash_from_uints; #[doc = " A function that returns a hash of a value @@ -313,17 +315,19 @@ fn bytes_hash() -> hashmap<[u8], V> { ret hashmap(vec::u8::hash, vec::u8::eq); } +fn hash_int(&&x: int) -> uint { int::hash(x) } +fn eq_int(&&a: int, &&b: int) -> bool { ret a == b; } + #[doc = "Construct a hashmap for int keys"] fn int_hash() -> hashmap { - fn hash_int(&&x: int) -> uint { int::hash(x) } - fn eq_int(&&a: int, &&b: int) -> bool { ret a == b; } ret hashmap(hash_int, eq_int); } +fn hash_uint(&&x: uint) -> uint { uint::hash(x) } +fn eq_uint(&&a: uint, &&b: uint) -> bool { ret a == b; } + #[doc = "Construct a hashmap for uint keys"] fn uint_hash() -> hashmap { - fn hash_uint(&&x: uint) -> uint { uint::hash(x) } - fn eq_uint(&&a: uint, &&b: uint) -> bool { ret a == b; } ret hashmap(hash_uint, eq_uint); } @@ -332,6 +336,37 @@ Convenience function for adding keys to a hashmap with nil type keys "] fn set_add(set: set, key: K) -> bool { ret set.insert(key, ()); } +#[doc = "Construct a hashmap from a vector"] +fn hash_from_vec(hasher: hashfn, eqer: eqfn, + items: [(K, V)]) -> hashmap { + let map = hashmap(hasher, eqer); + vec::iter(items) { |item| + let (key, value) = item; + map.insert(key, value); + } + map +} + +#[doc = "Construct a hashmap from a vector with string keys"] +fn hash_from_strs(items: [(str, V)]) -> hashmap { + hash_from_vec(str::hash, str::eq, items) +} + +#[doc = "Construct a hashmap from a vector with byte keys"] +fn hash_from_bytes(items: [([u8], V)]) -> hashmap<[u8], V> { + hash_from_vec(vec::u8::hash, vec::u8::eq, items) +} + +#[doc = "Construct a hashmap from a vector with int keys"] +fn hash_from_ints(items: [(int, V)]) -> hashmap { + hash_from_vec(hash_int, eq_int, items) +} + +#[doc = "Construct a hashmap from a vector with uint keys"] +fn hash_from_uints(items: [(uint, V)]) -> hashmap { + hash_from_vec(hash_uint, eq_uint, items) +} + #[cfg(test)] mod tests { @@ -574,4 +609,17 @@ mod tests { map.insert(key, "val"); assert (option::get(map.find(key)) == "val"); } + + #[test] + fn test_hash_from_vec() { + let map = map::hash_from_strs([ + ("a", 1), + ("b", 2), + ("c", 3) + ]); + assert map.size() == 3u; + assert map.get("a") == 1; + assert map.get("b") == 2; + assert map.get("c") == 3; + } } -- cgit 1.4.1-3-g733a5