multimap icon indicating copy to clipboard operation
multimap copied to clipboard

insert() doesn't let you know if already existed or not

Open andrewdavidmackenzie opened this issue 4 years ago • 2 comments

The docs for mutlimap state:

A MultiMap implementation which is just a wrapper around std::collections::HashMap. See HashMap's documentation for more details.

but the HashMap docs here state

pub fn insert(&mut self, k: K, v: V) -> Option<V>
[src][−]
Inserts a key-value pair into the map.

If the map did not have this key present, None is returned.

If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be == without being identical. See the module-level documentation for more.

In particular I want to insert an entry into the multi-map and to know if an identical entry already existed in it (to avoid duplicates). The HashMap insert() method helped doing this, the MultiMap one does not.

I can obviously work around this, but thought it would be good if this mirrored the HashMap implementation more closely, from the consumer point of view. Although I see the disadvantage that here it will take more cycles to detect if a matching entry already existed.

andrewdavidmackenzie avatar Feb 25 '20 22:02 andrewdavidmackenzie

I tried to make the api as similar as possible to HashMap's api, but I probably made some mistakes :/

Fixing this one requires a breaking change and a mayor update. And maybe that should be fixed. I'll start a milestone for a mayor update and include this bug.

Regardless, could you use the following:

let mut m = MultiMap::new();
m.insert(1, 42);
let v = m.entry(1).or_insert_vec(vec![43]);
assert_eq!(v, &vec![42]);

or:

let mut m = MultiMap::new();
m.insert(1, 42);
let v = m.entry(1).or_insert(43);
assert_eq!(v, &42);

havarnov avatar Feb 26 '20 21:02 havarnov

Thanks for the alternative. Not high priority for my project now, as I have realized I need to NOT insert multiple times, so I need to check it's not there already before inserting.

andrewdavidmackenzie avatar Feb 28 '20 12:02 andrewdavidmackenzie