github.com/moontrade/nogc@v0.1.7/sync/hash.h (about) 1 #ifndef HASH_H 2 #define HASH_H 3 4 #pragma once 5 6 #include <cstddef> 7 #include <cstdint> 8 #include <string> 9 #include <type_traits> 10 11 static const char* HashName = "FNV1a"; 12 13 static size_t fnv1a(uint8_t const* data, size_t size) { 14 #if SIZE_MAX == UINT32_MAX 15 static constexpr size_t FNV_offset_basis = UINT64_C(14695981039346656037); 16 static constexpr size_t FNV_prime = UINT64_C(1099511628211); 17 #else 18 static constexpr size_t FNV_offset_basis = UINT32_C(2166136261); 19 static constexpr size_t FNV_prime = UINT32_C(16777619); 20 #endif 21 size_t val = FNV_offset_basis; 22 for (size_t i = 0; i < size; ++i) { 23 val ^= static_cast<size_t>(data[i]); 24 val *= FNV_prime; 25 } 26 return val; 27 } 28 29 // Visual Studio uses a FNV1a implementation. 30 template <typename T> 31 struct Hash { 32 size_t operator()(T const& key) const { 33 return fnv1a(reinterpret_cast<uint8_t const*>(&key), sizeof(T)); 34 } 35 }; 36 37 // Visual Studio uses a FNV1a implementation. 38 template <> 39 struct Hash<std::string> { 40 size_t operator()(std::string const& key) const { 41 return fnv1a(reinterpret_cast<uint8_t const*>(key.data()), key.size()); 42 } 43 }; 44 45 #endif //HASH_H