Skip to content

Commit 4ede63b

Browse files
committed
Add HashSet::get_or_insert_owned
1 parent caa231d commit 4ede63b

File tree

1 file changed

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

1 file changed

+32
-0
lines changed

src/libstd/collections/hash/set.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,38 @@ where
631631
self.map.raw_entry_mut().from_key(&value).or_insert(value, ()).0
632632
}
633633

634+
/// Inserts an owned copy of the given `value` into the set if it is not
635+
/// present, then returns a reference to the value in the set.
636+
///
637+
/// # Examples
638+
///
639+
/// ```
640+
/// #![feature(hash_set_entry)]
641+
///
642+
/// use std::collections::HashSet;
643+
///
644+
/// let mut set: HashSet<String> = ["cat", "dog", "horse"]
645+
/// .iter().map(|&pet| pet.to_owned()).collect();
646+
///
647+
/// assert_eq!(set.len(), 3);
648+
/// for &pet in &["cat", "dog", "fish"] {
649+
/// let value = set.get_or_insert_owned(pet);
650+
/// assert_eq!(value, pet);
651+
/// }
652+
/// assert_eq!(set.len(), 4); // a new "fish" was inserted
653+
/// ```
654+
#[inline]
655+
#[unstable(feature = "hash_set_entry", issue = "60896")]
656+
pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
657+
where
658+
T: Borrow<Q>,
659+
Q: Hash + Eq + ToOwned<Owned = T>,
660+
{
661+
// Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
662+
// `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
663+
self.map.raw_entry_mut().from_key(value).or_insert_with(|| (value.to_owned(), ())).0
664+
}
665+
634666
/// Inserts a value computed from `f` into the set if the given `value` is
635667
/// not present, then returns a reference to the value in the set.
636668
///

0 commit comments

Comments
 (0)