Cogs.Core
HashFunctions.h
1#pragma once
2
3#include "FoundationBase.h"
4
5#include <string_view>
6#include <type_traits>
7
14namespace Cogs
15{
26 [[nodiscard]]
27 COGSFOUNDATION_API size_t murmur2(const void* bytes, const size_t length) noexcept;
28
29 namespace Details
30 {
31 constexpr size_t FNV_offset_basis = (sizeof(size_t) == 8) ? static_cast<size_t>(14695981039346656037ULL) : 2166136261U;
32 constexpr size_t FNV_prime = (sizeof(size_t) == 8) ? static_cast<size_t>(1099511628211ULL) : 16777619U;
33 }
34
36 [[nodiscard]]
37 constexpr size_t fnv1a(uint8_t data, size_t hashValue) noexcept {
38 return (hashValue ^ data) * Details::FNV_prime;
39 }
40
52 [[nodiscard]]
53 constexpr size_t fnv1a(const void* bytes, size_t length, size_t hashValue = Details::FNV_offset_basis) noexcept {
54 for (const uint8_t* read = static_cast<const uint8_t*>(bytes); length--; ++read) {
55 hashValue = fnv1a(*read, hashValue);
56 }
57 return hashValue;
58 }
59
61 [[nodiscard]]
62 constexpr size_t hash() noexcept {
63 return Details::FNV_offset_basis;
64 }
65
67 template<typename T, typename std::enable_if<std::is_integral<T>::value || std::is_enum<T>::value || std::is_floating_point<T>::value, int>::type* = nullptr>
68 [[nodiscard]]
69 constexpr size_t hash(T data, size_t hashValue = hash()) noexcept {
70 return fnv1a(&data, sizeof(data), hashValue);
71 }
72
74 [[nodiscard]]
75 constexpr size_t hash(const char* str, size_t hashValue = hash()) noexcept {
76 for (; *str; ++str) {
77 hashValue = fnv1a(static_cast<uint8_t>(*str), hashValue);
78 }
79 return hashValue;
80 }
81
88 [[nodiscard]]
89 COGSFOUNDATION_API size_t hashLowercase(std::string_view str, size_t hashValue = Cogs::hash()) noexcept;
90
91
93 [[nodiscard]]
94 constexpr size_t hash(const void* mem, size_t size, size_t hashValue = hash()) noexcept {
95 return fnv1a(mem, size, hashValue);
96 }
97
99 [[nodiscard]]
100 constexpr size_t hash(std::string_view str, size_t hashValue = hash()) noexcept {
101 for (const char read : str) {
102 hashValue = fnv1a(read, hashValue);
103 }
104 return hashValue;
105 }
106}
Contains all Cogs related functionality.
Definition: FieldSetter.h:23
constexpr size_t hash() noexcept
Simple getter function that returns the initial value for fnv1a hashing.
Definition: HashFunctions.h:62
constexpr size_t fnv1a(uint8_t data, size_t hashValue) noexcept
Hashes a single byte using the fnv1a algorithm.
Definition: HashFunctions.h:37
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.