Skip to content

Commit 6e140a9

Browse files
committed
Add Entry::and_modify
1 parent 64dd1e0 commit 6e140a9

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

‎src/map.rs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,40 @@ impl<'a> Entry<'a> {
542542
Entry::Occupied(entry) => entry.into_mut(),
543543
}
544544
}
545+
546+
/// Provides in-place mutable access to an occupied entry before any
547+
/// potential inserts into the map.
548+
///
549+
/// # Examples
550+
///
551+
/// ```
552+
/// # use serde_json::json;
553+
/// #
554+
/// let mut map = serde_json::Map::new();
555+
/// map.entry("serde")
556+
/// .and_modify(|e| { *e = json!("rust") })
557+
/// .or_insert(json!("cpp"));
558+
///
559+
/// assert_eq!(map["serde"], "cpp".to_owned());
560+
///
561+
/// map.entry("serde")
562+
/// .and_modify(|e| { *e = json!("rust") })
563+
/// .or_insert(json!("cpp"));
564+
///
565+
/// assert_eq!(map["serde"], "rust".to_owned());
566+
/// ```
567+
pub fn and_modify<F>(self, f: F) -> Self
568+
where
569+
F: FnOnce(&mut Value),
570+
{
571+
match self {
572+
Entry::Occupied(mut entry) => {
573+
f(entry.get_mut());
574+
Entry::Occupied(entry)
575+
}
576+
Entry::Vacant(entry) => Entry::Vacant(entry),
577+
}
578+
}
545579
}
546580

547581
impl<'a> VacantEntry<'a> {

0 commit comments

Comments
 (0)