Skip to content

Commit

Permalink
Merge pull request 754 from Krout0n/entry#and_modify
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Feb 25, 2021
2 parents 64dd1e0 + 6e140a9 commit 461f2bf
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/map.rs
Expand Up @@ -542,6 +542,40 @@ impl<'a> Entry<'a> {
Entry::Occupied(entry) => entry.into_mut(),
}
}

/// Provides in-place mutable access to an occupied entry before any
/// potential inserts into the map.
///
/// # Examples
///
/// ```
/// # use serde_json::json;
/// #
/// let mut map = serde_json::Map::new();
/// map.entry("serde")
/// .and_modify(|e| *e = json!("rust"))
/// .or_insert(json!("cpp"));
///
/// assert_eq!(map["serde"], "cpp");
///
/// map.entry("serde")
/// .and_modify(|e| *e = json!("rust"))
/// .or_insert(json!("cpp"));
///
/// assert_eq!(map["serde"], "rust");
/// ```
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut Value),
{
match self {
Entry::Occupied(mut entry) => {
f(entry.get_mut());
Entry::Occupied(entry)
}
Entry::Vacant(entry) => Entry::Vacant(entry),
}
}
}

impl<'a> VacantEntry<'a> {
Expand Down

0 comments on commit 461f2bf

Please sign in to comment.