Counter based on HashMap

I want to use HashMap to implement a counter - entries can be incremented as well as decremented and if they reach 0 the key will be removed from the map.

The entry API has a convenient or_insert() method, but no "or_remove()" - is there a better way of decrementing than what I have done below?

fn map_inc(map: &mut HashMap<u64,usize>, k: u64) {
    map.entry(k).and_modify(|x| *x += 1).or_insert(1);
}

fn map_dec(map: &mut HashMap<u64,usize>, k: u64) {
    map
    .entry(k)
    .and_modify(|x| *x = if *x == 0 { 0 } else { *x - 1 });
    if let Some(count) = map.get(&k) {
        if *count == 0 {
            map.remove(&k);
        }
    }

}

Both can be simplified.

1 Like

Here's another version with fewer lookups.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.