From 6e140a91926dc149824ae64c81bf3790538ea722 Mon Sep 17 00:00:00 2001 From: Krouton Date: Thu, 25 Feb 2021 21:04:14 +0900 Subject: [PATCH] Add Entry::and_modify --- src/map.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/map.rs b/src/map.rs index f09d84059..2bc35107d 100644 --- a/src/map.rs +++ b/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(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> {