In-place deletion from HashMap and similar?


#1

Is there some way to delete items meeting a predicate from maps that doesn’t require using external memory? I could only find Vec::retain.

If the answer is no (which I suspect), I’m half-tempted to open an RFC to extend retain to other types. Is there any obvious issue that prevents it? I don’t want to go through the trouble of the RFC process if it’s very obvious why this method only exists for Vec.

My particular use case is removing items older than a certain time from a hashMap. The code I just wrote only has to deal with 4 or 5 items, so it’s not that big a deal. But I shortly need to write some code that deals with thousands of them.

Any help is appreciated.


#2

I don’t know any way to do this, but I think it sounds like a good idea.

The Entry API would almost let you do it with OccupiedEntry::remove(), but there’s no iterator for this AFAIK. A new iter_entries() could perhaps let you step through every OccupiedEntry, but I don’t think multiple can coexist (due to mutable aliasing of the table) as Iterator requires.

So yeah, a retain which handles entries one-by-one internally is probably best.


#3

It looks like the entry API might be usable for my other case if I write it differently than I was planning. I seem to be doing that a lot since I started Rust.

Unless someone comes up with some reason why this is a horrible idea in the next few days, I’ll go ahead and make an RFC for it.


#4

retain() has been added to HashMap in unstable https://doc.rust-lang.org/nightly/std/collections/struct.HashSet.html#method.retain