Skip to content

Commit

Permalink
Add entry-like methods to HashSet
Browse files Browse the repository at this point in the history
* `HashSet::get_or_insert`
* `HashSet::get_or_insert_with`

These provide a simplification of the `Entry` API for `HashSet`, with
names chosen to match the similar methods on `Option`.
  • Loading branch information
cuviper committed May 16, 2019
1 parent 7d5aa43 commit 5f93834
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/libstd/collections/hash/set.rs
Expand Up @@ -618,6 +618,58 @@ impl<T, S> HashSet<T, S>
self.map.get_key_value(value).map(|(k, _)| k)
}

/// Inserts 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<_> = [1, 2, 3].iter().cloned().collect();
/// assert_eq!(set.len(), 3);
/// assert_eq!(set.get_or_insert(2), &2);
/// assert_eq!(set.get_or_insert(100), &100);
/// assert_eq!(set.len(), 4); // 100 was inserted
/// ```
#[inline]
#[unstable(feature = "hash_set_entry", issue = "0")]
pub fn get_or_insert(&mut self, value: T) -> &T {
self.map.raw_entry_mut().from_key(&value).or_insert(value, ()).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.
///
/// # 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_with(pet, str::to_owned);
/// assert_eq!(value, pet);
/// }
/// assert_eq!(set.len(), 4); // a new "fish" was inserted
/// ```
#[inline]
#[unstable(feature = "hash_set_entry", issue = "0")]
pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
where T: Borrow<Q>,
Q: Hash + Eq,
F: FnOnce(&Q) -> T
{
self.map.raw_entry_mut().from_key(value).or_insert_with(|| (f(value), ())).0
}

/// Returns `true` if `self` has no elements in common with `other`.
/// This is equivalent to checking for an empty intersection.
///
Expand Down

0 comments on commit 5f93834

Please sign in to comment.