summaryrefslogtreecommitdiff
path: root/AK/HashMap.h
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2021-09-04 17:27:59 +0200
committerAndreas Kling <kling@serenityos.org>2021-09-04 20:30:56 +0200
commit1a71e20f93ceb113b067174e3a94124143d178d1 (patch)
treef638c5c6b6c33cd747e966262a0f18375396f89c /AK/HashMap.h
parent0094259d72fe0f9cbf00bf3fa78f157ffb49f5e4 (diff)
downloadserenity-1a71e20f93ceb113b067174e3a94124143d178d1.zip
AK: Add HashMap::ensure(key, callback)
This function ensures that a key is present in the HashMap. If it's not present, it is inserted, and the corresponding value is initialized with whatever the callback returns. It allows us to express this: auto it = map.find(key); if (it == map.end()) { map.set(it, make_a_value()); it = map.find(key); } auto& value = it->value; Like this: auto& value = map.ensure(key, [] { return make_a_value(); }); Note that the callback is only invoked if we have to insert a missing key into the HashMap. This is important in case constructing the default value is expensive or otherwise undesirable.
Diffstat (limited to 'AK/HashMap.h')
-rw-r--r--AK/HashMap.h10
1 files changed, 10 insertions, 0 deletions
diff --git a/AK/HashMap.h b/AK/HashMap.h
index e5e9bb66fd..3eb103abdd 100644
--- a/AK/HashMap.h
+++ b/AK/HashMap.h
@@ -139,6 +139,16 @@ public:
return find(key)->value;
}
+ template<typename Callback>
+ V& ensure(K const& key, Callback initialization_callback)
+ {
+ auto it = find(key);
+ if (it == end()) {
+ set(key, initialization_callback());
+ }
+ return find(key)->value;
+ }
+
[[nodiscard]] Vector<K> keys() const
{
Vector<K> list;