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:
parent
c516715e62
commit
c9de6cbc51
1 changed files with 5 additions and 10 deletions
15
AK/HashMap.h
15
AK/HashMap.h
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue