-
Notifications
You must be signed in to change notification settings - Fork 0
/
commUtil.h
112 lines (89 loc) · 1.92 KB
/
commUtil.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#pragma once
#ifdef _MSC_VER
template <size_t N>
struct EnsureConst
{
static const size_t value = N;
};
#endif
// #define PRIME_NUM 0x9e3779b9
constexpr size_t PrimeNum()
{
// UINT32_MAX * 0.61803398875 + 0.5
return sizeof(size_t) == 4
? 0x9e3779b9 : 0x9e3779b97f681800;
}
#ifdef _MSC_VER
#define PRIME_NUM (EnsureConst<PrimeNum()>::value)
#else
#define PRIME_NUM (PrimeNum())
#endif
constexpr size_t _Hash(char const * str, size_t seed)
{
return 0 == *str ? seed : _Hash(str + 1, seed ^ (*str + PRIME_NUM + (seed << 6) + (seed >> 2)));
}
#ifdef _MSC_VER
#define CT_HASH(x) (EnsureConst<_Hash(x, 0)>::value)
#else
#define CT_HASH(x) (_Hash(x, 0))
#endif
template <typename SizeT>
inline void HashCombineImpl(SizeT& seed, SizeT value)
{
seed ^= value + PRIME_NUM + (seed << 6) + (seed >> 2);
}
inline size_t RT_HASH(char const * str)
{
size_t seed = 0;
while (*str != 0)
{
HashCombineImpl(seed, static_cast<size_t>(*str));
++str;
}
return seed;
}
#undef PRIME_NUM
template <typename T>
inline size_t HashValue(T v)
{
return static_cast<size_t>(v);
}
template <typename T>
inline size_t HashValue(T* v)
{
return static_cast<size_t>(reinterpret_cast<ptrdiff_t>(v));
}
template <typename T>
inline void HashCombine(size_t& seed, T const & v)
{
return HashCombineImpl(seed, HashValue(v));
}
template <typename T>
inline void HashRange(size_t& seed, T first, T const & last)
{
for (; first != last; ++first)
{
HashCombine(seed, *first);
}
}
template <typename T>
inline size_t HashRange(T first, T const & last)
{
size_t seed = 0;
HashRange(seed, first, last);
return seed;
}
template <typename T = char, typename U>
inline size_t HashObj(U const & pObj)
{
T const * myBegin = reinterpret_cast<T const *>(&pObj);
T const * myEnd = myBegin + sizeof(U);
return HashRange(myBegin, myEnd);
}
#define ArrayCount(x) (sizeof(x) / sizeof((x)[0]))
#define SafeDelete(x) { \
if (x) { \
delete x; \
x = nullptr; \
} \
}