Skip to content

Commit 1fc6ad5

Browse files
committed
Add HashMap::remove_entry
Implements #46344
1 parent 8724337 commit 1fc6ad5

File tree

1 file changed

+49
-1
lines changed
  • src/libstd/collections/hash

1 file changed

+49
-1
lines changed

src/libstd/collections/hash/map.rs

+49-1
Original file line numberDiff line numberDiff line change
@@ -1241,6 +1241,46 @@ impl<K, V, S> HashMap<K, V, S>
12411241
self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
12421242
}
12431243

1244+
/// Removes a key from the map, returning the stored key and value if the
1245+
/// key was previously in the map.
1246+
///
1247+
/// The key may be any borrowed form of the map's key type, but
1248+
/// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1249+
/// the key type.
1250+
///
1251+
/// [`Eq`]: ../../std/cmp/trait.Eq.html
1252+
/// [`Hash`]: ../../std/hash/trait.Hash.html
1253+
///
1254+
/// # Examples
1255+
///
1256+
/// ```
1257+
/// #![feature(hash_map_remove_entry)]
1258+
/// use std::collections::HashMap;
1259+
///
1260+
/// # fn main() {
1261+
/// let mut map = HashMap::new();
1262+
/// map.insert(1, "a");
1263+
/// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1264+
/// assert_eq!(map.remove(&1), None);
1265+
/// # }
1266+
/// ```
1267+
#[unstable(feature = "hash_map_remove_entry", issue = "46344")]
1268+
pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1269+
where K: Borrow<Q>,
1270+
Q: Hash + Eq
1271+
{
1272+
if self.table.size() == 0 {
1273+
return None;
1274+
}
1275+
1276+
self.search_mut(k)
1277+
.into_occupied_bucket()
1278+
.map(|bucket| {
1279+
let (k, v, _) = pop_internal(bucket);
1280+
(k, v)
1281+
})
1282+
}
1283+
12441284
/// Retains only the elements specified by the predicate.
12451285
///
12461286
/// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
@@ -3040,13 +3080,21 @@ mod test_map {
30403080
}
30413081

30423082
#[test]
3043-
fn test_pop() {
3083+
fn test_remove() {
30443084
let mut m = HashMap::new();
30453085
m.insert(1, 2);
30463086
assert_eq!(m.remove(&1), Some(2));
30473087
assert_eq!(m.remove(&1), None);
30483088
}
30493089

3090+
#[test]
3091+
fn test_remove_entry() {
3092+
let mut m = HashMap::new();
3093+
m.insert(1, 2);
3094+
assert_eq!(m.remove_entry(&1), Some((1, 2)));
3095+
assert_eq!(m.remove(&1), None);
3096+
}
3097+
30503098
#[test]
30513099
fn test_iterate() {
30523100
let mut m = HashMap::with_capacity(4);

0 commit comments

Comments
 (0)