AK: Implement HashMap::ensure(key) in terms of ensure(key, callback)

In cases where the key is not present, the previous implementation
would do three lookups, when only one should be necessary, as a bucket
must exist after the method returns.
This commit is contained in:
Zaggy1024 2025-12-18 18:01:18 -06:00 committed by Gregory Bertilson
parent c516715e62
commit c9de6cbc51

View file

@ -265,22 +265,17 @@ public:
return take(begin()->key).release_value();
}
V& ensure(K const& key)
{
auto it = find(key);
if (it != end())
return it->value;
auto result = set(key, V());
VERIFY(result == HashSetResult::InsertedNewEntry);
return find(key)->value;
}
template<typename Callback>
V& ensure(K const& key, Callback initialization_callback, HashSetExistingEntryBehavior existing_entry_behavior = HashSetExistingEntryBehavior::Keep)
{
return m_table.ensure(KeyTraits::hash(key), [&](auto& entry) { return KeyTraits::equals(entry.key, key); }, [&] -> Entry { return { key, initialization_callback() }; }, existing_entry_behavior).value;
}
V& ensure(K const& key)
{
return ensure(key, [] { return V(); });
}
template<typename Callback>
ErrorOr<V> try_ensure(K const& key, Callback initialization_callback)
{