From 950b36f95df23e2b11ef15351d0208699c7677ba Mon Sep 17 00:00:00 2001 From: Eli Youngs Date: Sat, 10 Dec 2022 18:03:02 -0800 Subject: [PATCH] AK: Add a try_ensure() method to HashMap --- AK/HashMap.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/AK/HashMap.h b/AK/HashMap.h index 2a036cc5ae..d4d56968e2 100644 --- a/AK/HashMap.h +++ b/AK/HashMap.h @@ -222,6 +222,17 @@ public: return find(key)->value; } + template + ErrorOr try_ensure(K const& key, Callback initialization_callback) + { + auto it = find(key); + if (it != end()) + return it->value; + auto result = TRY(try_set(key, initialization_callback())); + VERIFY(result == HashSetResult::InsertedNewEntry); + return find(key)->value; + } + [[nodiscard]] Vector keys() const { Vector list;