mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 00:37:35 +00:00
AK: Add hash traits for floating-point primitives
This allows us to use float and double as hash keys.
This commit is contained in:
parent
69ca27d3d7
commit
ae6b09f4dc
2 changed files with 38 additions and 0 deletions
14
AK/Traits.h
14
AK/Traits.h
|
@ -40,6 +40,20 @@ requires(IsIntegral<T>) struct Traits<T> : public GenericTraits<T> {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#ifndef KERNEL
|
||||||
|
template<typename T>
|
||||||
|
requires(IsFloatingPoint<T>) struct Traits<T> : public GenericTraits<T> {
|
||||||
|
static constexpr bool is_trivial() { return true; }
|
||||||
|
static constexpr unsigned hash(T value)
|
||||||
|
{
|
||||||
|
if constexpr (sizeof(T) < 8)
|
||||||
|
return int_hash(bit_cast<u32>(value));
|
||||||
|
else
|
||||||
|
return u64_hash(bit_cast<u64>(value));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
requires(IsPointer<T> && !Detail::IsPointerOfType<char, T>) struct Traits<T> : public GenericTraits<T> {
|
requires(IsPointer<T> && !Detail::IsPointerOfType<char, T>) struct Traits<T> : public GenericTraits<T> {
|
||||||
static unsigned hash(T p) { return ptr_hash((FlatPtr)p); }
|
static unsigned hash(T p) { return ptr_hash((FlatPtr)p); }
|
||||||
|
|
|
@ -256,6 +256,30 @@ TEST_CASE(non_trivial_type_table)
|
||||||
EXPECT_EQ(table.remove_all_matching([&](auto&) { return true; }), false);
|
EXPECT_EQ(table.remove_all_matching([&](auto&) { return true; }), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE(floats)
|
||||||
|
{
|
||||||
|
HashTable<float> table;
|
||||||
|
table.set(0);
|
||||||
|
table.set(1.0f);
|
||||||
|
table.set(2.0f);
|
||||||
|
EXPECT_EQ(table.size(), 3u);
|
||||||
|
EXPECT(table.contains(0));
|
||||||
|
EXPECT(table.contains(1.0f));
|
||||||
|
EXPECT(table.contains(2.0f));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE(doubles)
|
||||||
|
{
|
||||||
|
HashTable<double> table;
|
||||||
|
table.set(0);
|
||||||
|
table.set(1.0);
|
||||||
|
table.set(2.0);
|
||||||
|
EXPECT_EQ(table.size(), 3u);
|
||||||
|
EXPECT(table.contains(0));
|
||||||
|
EXPECT(table.contains(1.0));
|
||||||
|
EXPECT(table.contains(2.0));
|
||||||
|
}
|
||||||
|
|
||||||
// Inserting and removing a bunch of elements will "thrash" the table, leading to a lot of "deleted" markers.
|
// Inserting and removing a bunch of elements will "thrash" the table, leading to a lot of "deleted" markers.
|
||||||
BENCHMARK_CASE(benchmark_thrashing)
|
BENCHMARK_CASE(benchmark_thrashing)
|
||||||
{
|
{
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue