[x] Tests for the changes have been added / updated.
[x] Documentation comments have been added / updated.
[x] A changelog entry has been made for the appropriate packages.
[x] Format code with the nightly rustfmt (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, and update_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 to update, 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 make update_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.
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.