@@ -601,6 +601,56 @@ where
601
601
self . map . get_key_value ( value) . map ( |( k, _) | k)
602
602
}
603
603
604
+ /// Inserts the given `value` into the set if it is not present, then
605
+ /// returns a reference to the value in the set.
606
+ ///
607
+ /// # Examples
608
+ ///
609
+ /// ```
610
+ /// use hashbrown::HashSet;
611
+ ///
612
+ /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
613
+ /// assert_eq!(set.len(), 3);
614
+ /// assert_eq!(set.get_or_insert(2), &2);
615
+ /// assert_eq!(set.get_or_insert(100), &100);
616
+ /// assert_eq!(set.len(), 4); // 100 was inserted
617
+ /// ```
618
+ #[ inline]
619
+ pub fn get_or_insert ( & mut self , value : T ) -> & T {
620
+ // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
621
+ // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
622
+ self . map . raw_entry_mut ( ) . from_key ( & value) . or_insert ( value, ( ) ) . 0
623
+ }
624
+
625
+ /// Inserts a value computed from `f` into the set if the given `value` is
626
+ /// not present, then returns a reference to the value in the set.
627
+ ///
628
+ /// # Examples
629
+ ///
630
+ /// ```
631
+ /// use hashbrown::HashSet;
632
+ ///
633
+ /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
634
+ /// .iter().map(|&pet| pet.to_owned()).collect();
635
+ ///
636
+ /// assert_eq!(set.len(), 3);
637
+ /// for &pet in &["cat", "dog", "fish"] {
638
+ /// let value = set.get_or_insert_with(pet, str::to_owned);
639
+ /// assert_eq!(value, pet);
640
+ /// }
641
+ /// assert_eq!(set.len(), 4); // a new "fish" was inserted
642
+ /// ```
643
+ #[ inline]
644
+ pub fn get_or_insert_with < Q : ?Sized , F > ( & mut self , value : & Q , f : F ) -> & T
645
+ where T : Borrow < Q > ,
646
+ Q : Hash + Eq ,
647
+ F : FnOnce ( & Q ) -> T
648
+ {
649
+ // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
650
+ // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
651
+ self . map . raw_entry_mut ( ) . from_key ( value) . or_insert_with ( || ( f ( value) , ( ) ) ) . 0
652
+ }
653
+
604
654
/// Returns `true` if `self` has no elements in common with `other`.
605
655
/// This is equivalent to checking for an empty intersection.
606
656
///
0 commit comments