Skip to content
This repository has been archived by the owner on Feb 10, 2024. It is now read-only.

Commit

Permalink
Auto merge of #44734 - mchlrhw:wip/hashmap-entry-and-then, r=BurntSushi
Browse files Browse the repository at this point in the history
Implement `and_modify` on `Entry`

## Motivation

`Entry`s are useful for allowing access to existing values in a map while also allowing default values to be inserted for absent keys. The existing API is similar to that of `Option`, where `or` and `or_with` can be used if the option variant is `None`.

The `Entry` API is, however, missing an equivalent of `Option`'s `and_then` method. If it were present it would be possible to modify an existing entry before calling `or_insert` without resorting to matching on the entry variant.

Tracking issue: rust-lang/rust#44733.
  • Loading branch information
bors committed Oct 6, 2017
2 parents 11b728d + 919f5af commit eea5bba
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2013,6 +2013,41 @@ impl<'a, K, V> Entry<'a, K, V> {
Vacant(ref entry) => entry.key(),
}
}

/// Provides in-place mutable access to an occupied entry before any
/// potential inserts into the map.
///
/// # Examples
///
/// ```
/// #![feature(entry_and_modify)]
/// use std::collections::HashMap;
///
/// let mut map: HashMap<&str, u32> = HashMap::new();
///
/// map.entry("poneyland")
/// .and_modify(|e| { *e += 1 })
/// .or_insert(42);
/// assert_eq!(map["poneyland"], 42);
///
/// map.entry("poneyland")
/// .and_modify(|e| { *e += 1 })
/// .or_insert(42);
/// assert_eq!(map["poneyland"], 43);
/// ```
#[unstable(feature = "entry_and_modify", issue = "44733")]
pub fn and_modify<F>(self, mut f: F) -> Self
where F: FnMut(&mut V)
{
match self {
Occupied(mut entry) => {
f(entry.get_mut());
Occupied(entry)
},
Vacant(entry) => Vacant(entry),
}
}

}

impl<'a, K, V: Default> Entry<'a, K, V> {
Expand Down

0 comments on commit eea5bba

Please sign in to comment.