actix-extras
actix-extras copied to clipboard
implement contains_key, update, update_or
PR Type
Feature
PR Checklist
- [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_keychecks if a key exists in the map, delegating to the underlying HashMap. This makes it a little easier than using.entries().updatetakes 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_oris 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 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.