mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-25 09:00:22 +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
Notes:
sideshowbarker
2024-07-17 14:11:45 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/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>
|
||||
requires(IsPointer<T> && !Detail::IsPointerOfType<char, T>) struct Traits<T> : public GenericTraits<T> {
|
||||
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);
|
||||
}
|
||||
|
||||
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.
|
||||
BENCHMARK_CASE(benchmark_thrashing)
|
||||
{
|
||||
|
|
Loading…
Reference in a new issue