implement contains_key, update, update_or #459
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Type
Feature
PR Checklist
cargo +nightly fmt
).Overview
It's quite common to want to update a value based on its existence in a map, and its current value. The typical case being incrementing counters. Right now this is a bit cumbersome, as you have to do a handle error states for serialize/deserialize and then an insert/update.
This PR adds
contains_key
,update
, andupdate_or
methods.contains_key
checks if a key exists in the map, delegating to the underlying HashMap. This makes it a little easier than using.entries()
.update
takes a key and a closure that takes the current value and sets the returned value. If the key doesn't exist, the closure is not called and the key is not inserted.update_or
is similar toupdate
, but takes a default value to insert if the key doesn't exist, kind of like an "emplace" or "upsert" or equivalent.My core use case is probably
update_or
, but the other two feel like a natural fit in terms of ergonomics, and are kind of required to makeupdate_or
work.I come with an open mind and I'm happy to hear feedback on the API design, or otherwise if you don't think this is a good fit feel free to close the PR.