diff --git a/src/libstd/map.rs b/src/libstd/map.rs index d6feebc016c8..041346c9cd9c 100644 --- a/src/libstd/map.rs +++ b/src/libstd/map.rs @@ -773,4 +773,25 @@ mod tests { assert map.get(~"b") == 2; assert map.get(~"c") == 3; } + + #[test] + fn test_insert_with_key() { + let map = map::HashMap::<~str, uint>(); + + fn inc(k: ~str, v0: uint, v1: uint) -> uint { + v0 + v1 + } + + map.insert_with_key(inc, ~"cat", 1); + map.insert_with_key(inc, ~"mongoose", 1); + map.insert_with_key(inc, ~"cat", 7); + map.insert_with_key(inc, ~"ferret", 3); + map.insert_with_key(inc, ~"cat", 2); + + assert 10 == option::get(map.find(~"cat")); + assert 3 == option::get(map.find(~"ferret")); + assert 1 == option::get(map.find(~"mongoose")); + + assert None == map.find(~"unicorn"); + } } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index bf94e11980a6..42198a6d7896 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -69,10 +69,7 @@ fn find(mm: HashMap<~[u8], uint>, key: ~str) -> uint { // given a map, increment the counter for a key fn update_freq(mm: HashMap<~[u8], uint>, key: &[u8]) { let key = vec::slice(key, 0, key.len()); - match mm.find(key) { - option::None => { mm.insert(key, 1u ); } - option::Some(val) => { mm.insert(key, 1u + val); } - } + mm.insert_with_key(|k,v,v1| {v + v1}, key, 1); } // given a ~[u8], for each window call a function diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 9bc7abfdff78..f582ac6737df 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -66,10 +66,7 @@ fn find(mm: HashMap<~[u8], uint>, key: ~str) -> uint { // given a map, increment the counter for a key fn update_freq(mm: HashMap<~[u8], uint>, key: &[u8]) { let key = vec::slice(key, 0, key.len()); - match mm.find(key) { - option::None => { mm.insert(key, 1u ); } - option::Some(val) => { mm.insert(key, 1u + val); } - } + mm.insert_with_key(|k,v,v1| {v + v1}, key, 1); } // given a ~[u8], for each window call a function