summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLinus Groh <mail@linusgroh.de>2020-12-28 12:49:16 +0100
committerAndreas Kling <kling@serenityos.org>2020-12-29 15:22:15 +0100
commit1ed72cc58086fcf4a784780dbdf476c76d81cfab (patch)
tree8272847a45a0b41f95d3ffaa7c3cad0b651d9053
parent1dbd26423901235191c7c6e2d5f696026faec149 (diff)
downloadserenity-1ed72cc58086fcf4a784780dbdf476c76d81cfab.zip
AK: Add HashMap(std::initializer_list<Entry>) constructor
This allows us to construct a HashMap from an initializer list like so: HashMap<K, V> hash_map = { { K, V }, { K, V } { K, V } };
-rw-r--r--AK/HashMap.h21
-rw-r--r--AK/Tests/TestHashMap.cpp11
2 files changed, 31 insertions, 1 deletions
diff --git a/AK/HashMap.h b/AK/HashMap.h
index cf1c8e22f1..424e14ac3d 100644
--- a/AK/HashMap.h
+++ b/AK/HashMap.h
@@ -31,6 +31,13 @@
#include <AK/StdLibExtras.h>
#include <AK/Vector.h>
+// NOTE: We can't include <initializer_list> during the toolchain bootstrap,
+// since it's part of libstdc++, and libstdc++ depends on LibC.
+// For this reason, we don't support HashMap(initializer_list) in LibC.
+#ifndef SERENITY_LIBC_BUILD
+# include <initializer_list>
+#endif
+
namespace AK {
template<typename K, typename V, typename KeyTraits>
@@ -49,7 +56,19 @@ private:
public:
HashMap() { }
- bool is_empty() const { return m_table.is_empty(); }
+#ifndef SERENITY_LIBC_BUILD
+ HashMap(std::initializer_list<Entry> list)
+ {
+ ensure_capacity(list.size());
+ for (auto& item : list)
+ set(item.key, item.value);
+ }
+#endif
+
+ bool is_empty() const
+ {
+ return m_table.is_empty();
+ }
size_t size() const { return m_table.size(); }
size_t capacity() const { return m_table.capacity(); }
void clear() { m_table.clear(); }
diff --git a/AK/Tests/TestHashMap.cpp b/AK/Tests/TestHashMap.cpp
index b38437600f..4b86bcd082 100644
--- a/AK/Tests/TestHashMap.cpp
+++ b/AK/Tests/TestHashMap.cpp
@@ -36,6 +36,17 @@ TEST_CASE(construct)
EXPECT_EQ(IntIntMap().size(), 0u);
}
+TEST_CASE(construct_from_initializer_list)
+{
+ HashMap<int, String> number_to_string {
+ { 1, "One" },
+ { 2, "Two" },
+ { 3, "Three" },
+ };
+ EXPECT_EQ(number_to_string.is_empty(), false);
+ EXPECT_EQ(number_to_string.size(), 3u);
+}
+
TEST_CASE(populate)
{
HashMap<int, String> number_to_string;