indexmap icon indicating copy to clipboard operation
indexmap copied to clipboard

Support `get_or_insert_with`

Open p4l1ly opened this issue 1 year ago • 5 comments

Could you please support something like this? https://docs.rs/hashbrown/latest/hashbrown/struct.HashSet.html#method.get_or_insert_with

p4l1ly avatar Oct 21 '24 08:10 p4l1ly

I would prefer to wait for the std version to stabilize, so we can make sure to match its final API. https://github.com/rust-lang/rust/issues/60896

(I authored that initially, but anyone could chase that to completion.)

cuviper avatar Oct 21 '24 16:10 cuviper

It's worth mentioning that the version by value, get_or_insert, is trivial with IndexSet::insert_full and then &set[i]. I'm sure we'll add that method too when the time comes, but it won't be any better than doing that yourself.

cuviper avatar Oct 21 '24 20:10 cuviper

My use case is kind of a micro-optimisation when I want to insert a possibly big borrowed value into the set. For efficiency reasons, I want to clone it only if it is not present. But IndexSet::insert_full takes ownership, so I have to clone it also if it is not stored. With get_or_insert_with I could do set.get_or_insert_with(value, |v| v.clone()).

p4l1ly avatar Oct 22 '24 04:10 p4l1ly

Yeah, understood. Another potential workaround is to make the clone cheaper, like wrapping the expensive part in Rc/Arc so it can be shared, but that's not always feasible.

cuviper avatar Oct 22 '24 15:10 cuviper

GIven how long it takes to stabilize the API in Rust,I think it would be beneficial to provide method to get_or_insert today and deal with deprecation later. To be frank I had to implement fn get_or_insert_default_with<Q, F>(&mut self, key: &Q, default: F) -> &mut V like three times by now for each container I work with and that's not fun -- don't get actual things done.

pronebird avatar Dec 30 '24 11:12 pronebird