-
Notifications
You must be signed in to change notification settings - Fork 287
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add HashSet::get_or_insert_with_mut
#396
base: master
Are you sure you want to change the base?
Conversation
This function avoids unnecessairy work when the value to be stored can take ownership of the lookup key, such as when interning. It makes a stronger guarantee than `HashSet::get_or_insert_with`, since the reference given to `f` is guaranteed to be unique, and thus safe to mutate. The functionality of this function can already be achieved by (ab)using `UnsafeCell`, but that relies on the implementation detail that the `&Q` given to `f` is unique.
To be honest, the implementation of this, as well as the #[test]
fn some_invalid_insert() {
let mut set = HashSet::new();
set.insert(1);
set.get_or_insert_with(&2, |_| 1);
set.get_or_insert_with(&3, |_| 1);
assert_eq!(vec![&1, &1, &1], set.iter().collect::<Vec<_>>());
} Can you at least document it? |
Oh wow, nice catch! In hindsight, I would have not have expected this behavior from a (safe) function called // This code doesn't borrow-check :(
if let Some(result) = self.get(value) {
result
} else {
self.insert_unique_unchecked(f(value))
} On that note, we also probably want a As for
My two cents: 1, 2) These would be the safest option, but it seems overly cautious. There are already other safe functions like 3) A separate 4) This would be a lot more self-documenting, and there is precedent for this, but: 4, 5) These are hard ones... It could be argued that I will just add a comment for now mentioning the expected invariants. |
…_insert_with_mut`
|
|
This function avoids unnecessairy work when the value to be stored can take ownership of the lookup key, such as when interning. It makes a stronger guarantee than
HashSet::get_or_insert_with
, since the reference given tof
is guaranteed to be unique, and thus safe to mutate.The functionality of this function can already be achieved by (ab)using
UnsafeCell
, but that relies on the implementation detail that the&Q
given tof
is unique.