From 4f86cd9f083e46e3fba0130cd63867ef7a37d763 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 17 Jun 2023 00:07:43 +0200 Subject: [PATCH] libluna: Add a so very basic HashMap --- libluna/include/luna/HashMap.h | 42 +++++++++++++++++++++++++++++++++ tests/libluna/TestHashTable.cpp | 15 ++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 libluna/include/luna/HashMap.h diff --git a/libluna/include/luna/HashMap.h b/libluna/include/luna/HashMap.h new file mode 100644 index 00000000..ba149304 --- /dev/null +++ b/libluna/include/luna/HashMap.h @@ -0,0 +1,42 @@ +#pragma once +#include + +template struct HashPair +{ + K key; + Option value; + + bool operator==(const HashPair& other) const + { + return key == other.key; + } +}; + +template u64 hash(const HashPair& value, u64 salt) +{ + return hash(value.key, salt); +} + +template struct HashMap +{ + public: + Result try_set(const K& key, const V& value) + { + return m_table.try_set(HashPair { key, value }); + } + + Option try_get(const K& key) + { + auto* p = m_table.try_find(HashPair { key, {} }); + if (!p) return {}; + return p->value; + } + + bool try_remove(const K& key) + { + return m_table.try_remove(HashPair { key, {} }); + } + + private: + HashTable> m_table; +}; diff --git a/tests/libluna/TestHashTable.cpp b/tests/libluna/TestHashTable.cpp index 27f56d28..5b410a24 100644 --- a/tests/libluna/TestHashTable.cpp +++ b/tests/libluna/TestHashTable.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -66,6 +67,19 @@ TestResult test_hash_table_duplicates() test_success; } +TestResult test_hash_map_set_and_get() +{ + HashMap map; + + validate(TRY(map.try_set(1, 42))); + + validate(map.try_get(1).release_value() == 42); + + validate(!map.try_get(6).has_value()); + + test_success; +} + Result test_main() { test_prelude; @@ -74,6 +88,7 @@ Result test_main() run_test(test_hash_table_find); run_test(test_hash_table_remove); run_test(test_hash_table_duplicates); + run_test(test_hash_map_set_and_get); return {}; }