Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/Common/include/Luau/HashUtil.h
2727 views
1
#pragma once
2
3
#include "Luau/Common.h"
4
5
#include <stddef.h>
6
#include <stdint.h>
7
8
#include <functional>
9
#include <type_traits>
10
#include <utility>
11
12
namespace Luau
13
{
14
15
struct DenseHashPointer
16
{
17
size_t operator()(const void* key) const
18
{
19
return (uintptr_t(key) >> 4) ^ (uintptr_t(key) >> 9);
20
}
21
};
22
23
namespace detail
24
{
25
26
template<typename T>
27
using DenseHashDefault = std::conditional_t<std::is_pointer_v<T>, DenseHashPointer, std::hash<T>>;
28
29
} // namespace detail
30
31
inline void hashCombine(size_t& seed, size_t hash)
32
{
33
// Golden Ratio constant used for better hash scattering
34
// See https://softwareengineering.stackexchange.com/a/402543
35
seed ^= hash + 0x9e3779b9 + (seed << 6) + (seed >> 2);
36
}
37
38
template<typename T1, typename T2, typename H1 = detail::DenseHashDefault<T1>, typename H2 = detail::DenseHashDefault<T2>>
39
struct PairHash
40
{
41
std::size_t operator()(const std::pair<T1, T2>& p) const noexcept
42
{
43
std::size_t seed = 0;
44
hashCombine(seed, h1(p.first));
45
hashCombine(seed, h2(p.second));
46
return seed;
47
}
48
49
private:
50
H1 h1;
51
H2 h2;
52
};
53
54
} // namespace Luau
55
56