Skip to content
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_owned #67358

Merged
merged 1 commit into from
Jan 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/libstd/collections/hash/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,38 @@ where
self.map.raw_entry_mut().from_key(&value).or_insert(value, ()).0
}

/// Inserts an owned copy of the given `value` into the set if it is not
/// present, then returns a reference to the value in the set.
///
/// # Examples
///
/// ```
/// #![feature(hash_set_entry)]
///
/// use std::collections::HashSet;
///
/// let mut set: HashSet<String> = ["cat", "dog", "horse"]
/// .iter().map(|&pet| pet.to_owned()).collect();
///
/// assert_eq!(set.len(), 3);
/// for &pet in &["cat", "dog", "fish"] {
/// let value = set.get_or_insert_owned(pet);
/// assert_eq!(value, pet);
/// }
/// assert_eq!(set.len(), 4); // a new "fish" was inserted
/// ```
#[inline]
#[unstable(feature = "hash_set_entry", issue = "60896")]
pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
where
T: Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = T>,
{
// Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
// `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
self.map.raw_entry_mut().from_key(value).or_insert_with(|| (value.to_owned(), ())).0
}

/// Inserts a value computed from `f` into the set if the given `value` is
/// not present, then returns a reference to the value in the set.
///
Expand Down