Skip to content

Commit

Permalink
In insert_unique_unchecked return a reference to just inserted key an…
Browse files Browse the repository at this point in the history
…d value
  • Loading branch information
stepancheg committed Sep 12, 2021
1 parent 8d6c278 commit b3bdc62
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
15 changes: 11 additions & 4 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1281,6 +1281,8 @@ where
/// Insert a key-value pair into the map without checking
/// if the key already exists in the map.
///
/// Returns a reference to the key and value just inserted.
///
/// This operation is safe if a key does not exist in the map.
///
/// However, if a key exists in the map already, the behavior is unspecified:
Expand All @@ -1297,10 +1299,13 @@ where
/// For example, when constructing a map from another map, we know
/// that keys are unique.
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_unique_unchecked(&mut self, k: K, v: V) {
pub fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
let hash = make_insert_hash::<K, S>(&self.hash_builder, &k);
self.table
let bucket = self
.table
.insert(hash, (k, v), make_hasher::<K, _, V, S>(&self.hash_builder));
let (k, v) = unsafe { bucket.as_mut() };
(k, v)
}

/// Tries to insert a key-value pair into the map, and returns
Expand Down Expand Up @@ -3926,8 +3931,10 @@ mod test_map {
#[test]
fn test_insert_unique_unchecked() {
let mut map = HashMap::new();
map.insert_unique_unchecked(10, 11);
map.insert_unique_unchecked(20, 21);
let (k, v) = map.insert_unique_unchecked(10, 11);
assert_eq!((&10, &mut 11), (k, v));
let (k, v) = map.insert_unique_unchecked(20, 21);
assert_eq!((&20, &mut 21), (k, v));
assert_eq!(Some(&11), map.get(&10));
assert_eq!(Some(&21), map.get(&20));
assert_eq!(None, map.get(&30));
Expand Down
6 changes: 4 additions & 2 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,8 @@ where

/// Insert a value the set without checking if the value already exists in the set.
///
/// Returns a reference to the value just inserted.
///
/// This operation is safe if a value does not exist in the set.
///
/// However, if a value exists in the set already, the behavior is unspecified:
Expand All @@ -1009,8 +1011,8 @@ where
/// For example, when constructing a set from another set, we know
/// that values are unique.
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_unique_unchecked(&mut self, value: T) {
self.map.insert_unique_unchecked(value, ());
pub fn insert_unique_unchecked(&mut self, value: T) -> &T {
self.map.insert_unique_unchecked(value, ()).0
}

/// Adds a value to the set, replacing the existing value, if any, that is equal to the given
Expand Down

0 comments on commit b3bdc62

Please sign in to comment.