Skip to content

Commit

Permalink
Enable usage of wider/custom keys
Browse files Browse the repository at this point in the history
  • Loading branch information
crocdialer committed Sep 29, 2024
1 parent 9269f30 commit 52b6704
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
10 changes: 5 additions & 5 deletions include/vierkant/linear_hashmap.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class linear_hashmap
inline void clear()
{
storage_item_t *ptr = m_storage.get(), *end = ptr + m_capacity;
for(; ptr != end; ++ptr) { ptr->key = 0; }
for(; ptr != end; ++ptr) { ptr->key = key_t(); }
}

value_t &put(const key_t &key, value_t value)
Expand All @@ -68,10 +68,10 @@ class linear_hashmap
if(probed_key != key)
{
// hit another entry, keep searching
if(probed_key != 0) { continue; }
if(probed_key != key_t()) { continue; }

item.key.compare_exchange_strong(probed_key, key, std::memory_order_relaxed, std::memory_order_relaxed);
if(probed_key && probed_key != key)
if((probed_key != key_t()) && (probed_key != key))
{
// another thread just stole it
continue;
Expand All @@ -91,7 +91,7 @@ class linear_hashmap
{
idx &= m_capacity - 1;
auto &item = m_storage[idx];
if(!item.key) { return {}; }
if(item.key == key_t()) { return {}; }
else if(key == item.key) { return item.value; }
}
}
Expand Down Expand Up @@ -124,7 +124,7 @@ class linear_hashmap
}

private:
struct alignas(16) storage_item_t
struct storage_item_t
{
std::atomic<key_t> key;
value_t value{};
Expand Down
25 changes: 23 additions & 2 deletions tests/TestLinearHashmap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,30 @@ TEST(linear_hashmap, basic)
EXPECT_EQ(hashmap.get(69), 99);
EXPECT_TRUE(hashmap.contains(13));
EXPECT_EQ(hashmap.get(13), 12);
}

TEST(linear_hashmap, custom_key)
{
// custom 32-byte key
struct custom_key_t
{
int v[8]{};
constexpr bool operator==(const custom_key_t &other) const
{
for(uint32_t i = 0; i < 8; ++i)
{
if(v[i] != other.v[i]) { return false; }
}
return true;
}
};
constexpr uint32_t test_capacity = 100;
auto hashmap = vierkant::linear_hashmap<custom_key_t, uint64_t>(test_capacity);

vierkant::linear_hashmap<uint64_t, uint64_t> other_map;
other_map = vierkant::linear_hashmap<uint64_t, uint64_t>(19);
custom_key_t k1{{1, 2, 3, 4, 5, 6, 7, 8}};
hashmap.put(k1, 69);
EXPECT_TRUE(hashmap.contains(k1));
EXPECT_FALSE(hashmap.contains(custom_key_t()));
}

TEST(linear_hashmap, resize)
Expand Down

0 comments on commit 52b6704

Please sign in to comment.