-
Notifications
You must be signed in to change notification settings - Fork 4
/
hash.h
42 lines (34 loc) · 1011 Bytes
/
hash.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
#pragma once
using fnv_t = unsigned;
class fnv_hash
{
static constexpr fnv_t FNV_PRIME = 16777619u;
static constexpr fnv_t OFFSET_BASIS = 2166136261u;
template <unsigned int N>
static constexpr fnv_t fnvHashConst( const char( &str )[N], unsigned int I = N )
{
return static_cast<fnv_t>( 1ULL * ( I == 1 ? ( OFFSET_BASIS ^ str[0] ) : ( fnvHashConst( str, I - 1 ) ^ str[I - 1] ) ) * FNV_PRIME );
}
static __forceinline fnv_t fnvHash( const char* str )
{
const auto length = strlen( str ) + 1;
auto hash = OFFSET_BASIS;
for ( size_t i = 0; i < length; ++i )
{
hash ^= *str++;
hash *= FNV_PRIME;
}
return hash;
}
struct Wrapper
{
Wrapper( const char* str ) : str( str ) { }
const char* str;
};
fnv_t hash_value;
public:
fnv_hash( Wrapper wrapper ) : hash_value( fnvHash( wrapper.str ) ) { }
template <unsigned int N>
constexpr fnv_hash( const char( &str )[N] ) : hash_value( fnvHashConst( str ) ) { }
constexpr operator fnv_t( ) const { return this->hash_value; }
};