From 836f984acd293b367d3a1f6f91f18fbfc17bdcde Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Tue, 25 Jan 2022 23:52:13 +1100 Subject: [PATCH] Add Entry::{or_default, and_modify} They were stabilised in 1.28.0 and 1.27.0. --- CHANGELOG.md | 2 ++ src/lib.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1be2128..7f76440 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ - Implemented `Default` on `Map` (not just on `RawMap`). +- Added `Entry::{or_default, and_modify}` (std::collections::hash_map parity). + - Removed the `anymap::raw` wrapper layer around `std::collections::hash_map`, in favour of exposing the raw `HashMap` directly. I think there was a reason I did it that seven years ago, but I think that reason may have dissolved by diff --git a/src/lib.rs b/src/lib.rs index beef1bd..4e8a7eb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -409,6 +409,34 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> Entry<'a, A, V> { Entry::Vacant(inner) => inner.insert(default()), } } + + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a mutable reference to the value in the entry. + #[inline] + pub fn or_default(self) -> &'a mut V where V: Default { + match self { + Entry::Occupied(inner) => inner.into_mut(), + Entry::Vacant(inner) => inner.insert(Default::default()), + } + } + + /// Provides in-place mutable access to an occupied entry before any potential inserts into the + /// map. + #[inline] + // std::collections::hash_map::Entry::and_modify doesn’t have #[must_use], I’ll follow suit. + #[allow(clippy::return_self_not_must_use)] + pub fn and_modify(self, f: F) -> Self { + match self { + Entry::Occupied(mut inner) => { + f(inner.get_mut()); + Entry::Occupied(inner) + }, + Entry::Vacant(inner) => Entry::Vacant(inner), + } + } + + // Additional stable methods (as of 1.60.0-nightly) that could be added: + // insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> (1.59.0) } impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> OccupiedEntry<'a, A, V> { -- 2.42.0