libluna: Add a so very basic HashMap
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
parent
32d2e0e6b7
commit
4f86cd9f08
42
libluna/include/luna/HashMap.h
Normal file
42
libluna/include/luna/HashMap.h
Normal 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;
|
||||
};
|
@ -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 {};
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user