Skip to content

Commit 5f93834

Browse files
committed
Add entry-like methods to HashSet
* `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`.
1 parent 7d5aa43 commit 5f93834

File tree

1 file changed

+52
-0
lines changed
  • src/libstd/collections/hash

1 file changed

+52
-0
lines changed

src/libstd/collections/hash/set.rs

+52
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,58 @@ impl<T, S> HashSet<T, S>
618618
self.map.get_key_value(value).map(|(k, _)| k)
619619
}
620620

621+
/// Inserts the given `value` into the set if it is not present, then
622+
/// returns a reference to the value in the set.
623+
///
624+
/// # Examples
625+
///
626+
/// ```
627+
/// #![feature(hash_set_entry)]
628+
///
629+
/// use std::collections::HashSet;
630+
///
631+
/// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
632+
/// assert_eq!(set.len(), 3);
633+
/// assert_eq!(set.get_or_insert(2), &2);
634+
/// assert_eq!(set.get_or_insert(100), &100);
635+
/// assert_eq!(set.len(), 4); // 100 was inserted
636+
/// ```
637+
#[inline]
638+
#[unstable(feature = "hash_set_entry", issue = "0")]
639+
pub fn get_or_insert(&mut self, value: T) -> &T {
640+
self.map.raw_entry_mut().from_key(&value).or_insert(value, ()).0
641+
}
642+
643+
/// Inserts a value computed from `f` into the set if the given `value` is
644+
/// not present, then returns a reference to the value in the set.
645+
///
646+
/// # Examples
647+
///
648+
/// ```
649+
/// #![feature(hash_set_entry)]
650+
///
651+
/// use std::collections::HashSet;
652+
///
653+
/// let mut set: HashSet<String> = ["cat", "dog", "horse"]
654+
/// .iter().map(|&pet| pet.to_owned()).collect();
655+
///
656+
/// assert_eq!(set.len(), 3);
657+
/// for &pet in &["cat", "dog", "fish"] {
658+
/// let value = set.get_or_insert_with(pet, str::to_owned);
659+
/// assert_eq!(value, pet);
660+
/// }
661+
/// assert_eq!(set.len(), 4); // a new "fish" was inserted
662+
/// ```
663+
#[inline]
664+
#[unstable(feature = "hash_set_entry", issue = "0")]
665+
pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
666+
where T: Borrow<Q>,
667+
Q: Hash + Eq,
668+
F: FnOnce(&Q) -> T
669+
{
670+
self.map.raw_entry_mut().from_key(value).or_insert_with(|| (f(value), ())).0
671+
}
672+
621673
/// Returns `true` if `self` has no elements in common with `other`.
622674
/// This is equivalent to checking for an empty intersection.
623675
///

0 commit comments

Comments
 (0)