libluna: Add a so very basic HashMap
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-06-17 00:07:43 +02:00
parent 32d2e0e6b7
commit 4f86cd9f08
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,42 @@
#pragma once
#include <luna/HashTable.h>
template <typename K, typename V> struct HashPair
{
K key;
Option<V> value;
bool operator==(const HashPair<K, V>& other) const
{
return key == other.key;
}
};
template <typename K, typename V> u64 hash(const HashPair<K, V>& value, u64 salt)
{
return hash(value.key, salt);
}
template <typename K, typename V> struct HashMap
{
public:
Result<bool> try_set(const K& key, const V& value)
{
return m_table.try_set(HashPair<K, V> { key, value });
}
Option<V> try_get(const K& key)
{
auto* p = m_table.try_find(HashPair<K, V> { key, {} });
if (!p) return {};
return p->value;
}
bool try_remove(const K& key)
{
return m_table.try_remove(HashPair<K, V> { key, {} });
}
private:
HashTable<HashPair<K, V>> m_table;
};

View File

@ -1,3 +1,4 @@
#include <luna/HashMap.h>
#include <luna/HashTable.h>
#include <os/File.h>
#include <test.h>
@ -66,6 +67,19 @@ TestResult test_hash_table_duplicates()
test_success;
}
TestResult test_hash_map_set_and_get()
{
HashMap<int, int> 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<void> test_main()
{
test_prelude;
@ -74,6 +88,7 @@ Result<void> 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 {};
}