Skip to content

Commit

Permalink
Add Object::get_mut_or_insert_with.
Browse files Browse the repository at this point in the history
  • Loading branch information
timothee-haudebourg committed Feb 16, 2024
1 parent 810b51f commit 16f5e79
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "json-syntax"
version = "0.11.6"
version = "0.11.7"
edition = "2021"
authors = ["Timothée Haudebourg <author@haudebourg.net>"]
description = "Strict JSON parsing and mapping library"
Expand Down
43 changes: 43 additions & 0 deletions src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,49 @@ impl Object {
}
}

/// Returns the (first) value associated to `key`, or insert a `key`-`value`
/// entry where `value` is returned by the given function `f`.
pub fn get_or_insert_with<Q: ?Sized>(&mut self, key: &Q, f: impl FnOnce() -> Value) -> &Value
where
Q: Hash + Equivalent<Key> + ToOwned,
Q::Owned: Into<Key>,
{
let index = match self.index_of(key) {
Some(index) => index,
None => {
let index = self.entries.len();
self.push(key.to_owned().into(), f());
index
}
};

&self.entries[index].value
}

/// Returns a mutable reference to the (first) value associated to `key`, or
/// insert a `key`-`value` entry where `value` is returned by the given
/// function `f`.
pub fn get_mut_or_insert_with<Q: ?Sized>(
&mut self,
key: &Q,
f: impl FnOnce() -> Value,
) -> &mut Value
where
Q: Hash + Equivalent<Key> + ToOwned,
Q::Owned: Into<Key>,
{
let index = match self.index_of(key) {
Some(index) => index,
None => {
let index = self.entries.len();
self.push(key.to_owned().into(), f());
index
}
};

&mut self.entries[index].value
}

pub fn index_of<Q: ?Sized>(&self, key: &Q) -> Option<usize>
where
Q: Hash + Equivalent<Key>,
Expand Down

0 comments on commit 16f5e79

Please sign in to comment.