diff --git a/AK/HashMap.h b/AK/HashMap.h index 9533b3042e..dedd185655 100644 --- a/AK/HashMap.h +++ b/AK/HashMap.h @@ -54,13 +54,16 @@ public: size_t capacity() const { return m_table.capacity(); } void clear() { m_table.clear(); } - void set(const K& key, const V& value) { m_table.set({ key, value }); } - void set(const K& key, V&& value) { m_table.set({ key, move(value) }); } - void remove(const K& key) + HashSetResult set(const K& key, const V& value) { return m_table.set({ key, value }); } + HashSetResult set(const K& key, V&& value) { return m_table.set({ key, move(value) }); } + bool remove(const K& key) { auto it = find(key); - if (it != end()) + if (it != end()) { m_table.remove(it); + return true; + } + return false; } void remove_one_randomly() { m_table.remove(m_table.begin()); } diff --git a/AK/HashTable.h b/AK/HashTable.h index 57a78fcc79..5a9d98eb00 100644 --- a/AK/HashTable.h +++ b/AK/HashTable.h @@ -34,6 +34,11 @@ namespace AK { +enum class HashSetResult { + InsertedNewEntry, + ReplacedExistingEntry +}; + template class HashTable; @@ -157,8 +162,8 @@ public: rehash(capacity); } - void set(const T&); - void set(T&&); + HashSetResult set(const T&); + HashSetResult set(T&&); bool contains(const T&) const; void clear(); @@ -208,11 +213,14 @@ public: return find(TraitsForT::hash(value), [&](auto& other) { return TraitsForT::equals(value, other); }); } - void remove(const T& value) + bool remove(const T& value) { auto it = find(value); - if (it != end()) + if (it != end()) { remove(it); + return true; + } + return false; } void remove(Iterator); @@ -251,7 +259,7 @@ private: }; template -void HashTable::set(T&& value) +HashSetResult HashTable::set(T&& value) { if (!m_capacity) rehash(1); @@ -259,7 +267,7 @@ void HashTable::set(T&& value) for (auto& e : bucket) { if (TraitsForT::equals(e, value)) { e = move(value); - return; + return HashSetResult::ReplacedExistingEntry; } } if (size() >= capacity()) { @@ -269,10 +277,11 @@ void HashTable::set(T&& value) bucket.append(move(value)); } m_size++; + return HashSetResult::InsertedNewEntry; } template -void HashTable::set(const T& value) +HashSetResult HashTable::set(const T& value) { if (!m_capacity) rehash(1); @@ -280,7 +289,7 @@ void HashTable::set(const T& value) for (auto& e : bucket) { if (TraitsForT::equals(e, value)) { e = value; - return; + return HashSetResult::ReplacedExistingEntry; } } if (size() >= capacity()) { @@ -290,6 +299,7 @@ void HashTable::set(const T& value) bucket.append(value); } m_size++; + return HashSetResult::InsertedNewEntry; } template