@@ -618,6 +618,58 @@ impl<T, S> HashSet<T, S>
618
618
self . map . get_key_value ( value) . map ( |( k, _) | k)
619
619
}
620
620
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
+
621
673
/// Returns `true` if `self` has no elements in common with `other`.
622
674
/// This is equivalent to checking for an empty intersection.
623
675
///
0 commit comments