@@ -631,6 +631,38 @@ where
631
631
self . map . raw_entry_mut ( ) . from_key ( & value) . or_insert ( value, ( ) ) . 0
632
632
}
633
633
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
+
634
666
/// Inserts a value computed from `f` into the set if the given `value` is
635
667
/// not present, then returns a reference to the value in the set.
636
668
///
0 commit comments