Cogs.Core
HashFunctions.cpp
1#include "HashFunctions.h"
2#include "HashSequence.h"
3
4size_t Cogs::murmur2(const void* bytes, const size_t length) noexcept
5{
6#if defined(_WIN64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(__LP64__)
7 const size_t m = 0xc6a4a7935bd1e995ull;
8 const int r = 47;
9#else
10 const size_t m = 0x5bd1e995;
11 const int r = 24;
12#endif
13
14 const size_t seed = 0;
15
16 size_t h = seed ^ (length * m);
17
18 const size_t * data = reinterpret_cast<const size_t *>(bytes);
19 const size_t * end = data + (length / sizeof(size_t));
20
21 while (data != end) {
22 size_t k = *data++;
23
24 k *= m;
25 k ^= k >> r;
26 k *= m;
27
28 h ^= k;
29 h *= m;
30 }
31
32 const uint8_t* trailing = reinterpret_cast<const uint8_t*>(data);
33
34#if defined(_WIN64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(__LP64__)
35 switch (length & 7) {
36 case 7: h ^= size_t(trailing[6]) << 48; [[fallthrough]];
37 case 6: h ^= size_t(trailing[5]) << 40; [[fallthrough]];
38 case 5: h ^= size_t(trailing[4]) << 32; [[fallthrough]];
39 case 4: h ^= size_t(trailing[3]) << 24; [[fallthrough]];
40#else
41 switch (length & 3) {
42#endif
43 case 3: h ^= size_t(trailing[2]) << 16; [[fallthrough]];
44 case 2: h ^= size_t(trailing[1]) << 8; [[fallthrough]];
45 case 1: h ^= size_t(trailing[0]);
46 h *= m;
47 break;
48 }
49
50 h ^= h >> r;
51 h *= m;
52 h ^= h >> r;
53
54 return h;
55}
56
57size_t Cogs::hashLowercase(std::string_view str, size_t hashValue) noexcept
58{
59 size_t strSize = str.size();
60 for (size_t i = 0; i < strSize; ++i) {
61 uint8_t chr = str[i];
62
63 // std::tolower uses C locale, avoid surprises and do it explicitly.
64 if (('A' <= chr) && (chr <= 'Z')) {
65 chr += 'a' - 'A';
66 }
67 hashValue = Cogs::hash(chr, hashValue);
68 }
69 return hashValue;
70}
constexpr size_t hash() noexcept
Simple getter function that returns the initial value for fnv1a hashing.
Definition: HashFunctions.h:62
COGSFOUNDATION_API size_t hashLowercase(std::string_view str, size_t hashValue=Cogs::hash()) noexcept
Get the hash code of the string converted to lowercase.
COGSFOUNDATION_API size_t murmur2(const void *bytes, const size_t length) noexcept
Implementation of the MurmurHash2 algorithm.