orlp / slotmap

Slotmap data structure for Rust
zlib License
1.12k stars 70 forks source link

Add try_insert_with_key that accepts a fallible closure #74

Closed caelunshun closed 2 years ago

caelunshun commented 3 years ago

Adds a new try_insert_with_key method to SlotMap, DenseSlotMap, and HopSlotMap. This method accepts a closure returning a Result. If the closure returns an error, try_insert_with_key leaves the slotmap untouched and returns the error.

This is useful when value construction is fallible.

orlp commented 3 years ago

If you address my comments in all three variants this seems like a nice addition.

orlp commented 3 years ago

We might get better code generation if we do

#[derive(Debug)]
enum Never { }
self.try_insert_with_key::<_, Never>(move |k| Ok(f(k))).unwrap()
caelunshun commented 3 years ago

Sounds good. I've addressed your comments and used the Never trick.