]> git.proxmox.com Git - cargo.git/blobdiff - vendor/serde_json/src/map.rs
New upstream version 0.52.0
[cargo.git] / vendor / serde_json / src / map.rs
index f09d840590c7d179478e0e793c71b1dab6d4a5c1..b5644461a28bfaea4fbcccb46ed0004e2e932a48 100644 (file)
@@ -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> {