mirror of
https://github.com/serde-rs/json.git
synced 2025-09-30 14:32:05 +00:00
Add Entry::and_modify
This commit is contained in:
parent
64dd1e03e0
commit
6e140a9192
34
src/map.rs
34
src/map.rs
@ -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".to_owned());
|
||||
///
|
||||
/// map.entry("serde")
|
||||
/// .and_modify(|e| { *e = json!("rust") })
|
||||
/// .or_insert(json!("cpp"));
|
||||
///
|
||||
/// assert_eq!(map["serde"], "rust".to_owned());
|
||||
/// ```
|
||||
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> {
|
||||
|
Loading…
x
Reference in New Issue
Block a user