hash.hh (2003B)
1 #ifndef hash_hh_INCLUDED 2 #define hash_hh_INCLUDED 3 4 #include <type_traits> 5 #include <utility> 6 7 #include <cstddef> 8 #include <cstdint> 9 10 namespace Kakoune 11 { 12 13 inline size_t fnv1a(const char* data, size_t len) 14 { 15 constexpr uint32_t FNV_prime_32 = 16777619; 16 constexpr uint32_t offset_basis_32 = 2166136261; 17 18 uint32_t hash_value = offset_basis_32; 19 for (size_t i = 0; i < len; ++i) 20 hash_value = (hash_value ^ data[i]) * FNV_prime_32; 21 return hash_value; 22 } 23 24 size_t murmur3(const char* input, size_t len); 25 26 template<typename Type> requires std::is_integral_v<Type> 27 constexpr size_t hash_value(const Type& val) 28 { 29 return (size_t)val; 30 } 31 32 template<typename Type> requires std::is_enum_v<Type> 33 constexpr size_t hash_value(const Type& val) 34 { 35 return hash_value((std::underlying_type_t<Type>)val); 36 } 37 38 template<typename Type> 39 constexpr size_t hash_values(Type&& t) 40 { 41 return hash_value(std::forward<Type>(t)); 42 } 43 44 constexpr size_t combine_hash(size_t lhs, size_t rhs) 45 { 46 return lhs ^ (rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2)); 47 } 48 49 template<typename Type, typename... RemainingTypes> 50 constexpr size_t hash_values(Type&& t, RemainingTypes&&... rt) 51 { 52 size_t seed = hash_values(std::forward<RemainingTypes>(rt)...); 53 return combine_hash(seed, hash_value(std::forward<Type>(t))); 54 } 55 56 template<typename T1, typename T2> 57 constexpr size_t hash_value(const std::pair<T1, T2>& val) 58 { 59 return hash_values(val.first, val.second); 60 } 61 62 template<typename Type> 63 struct Hash 64 { 65 constexpr size_t operator()(const Type& val) const 66 { 67 return hash_value(val); 68 } 69 }; 70 71 // Traits specifying if two types have compatible hashing, that is, 72 // if lhs == rhs => hash_value(lhs) == hash_value(rhs) 73 template<typename Lhs, typename Rhs> 74 struct HashCompatible : std::false_type {}; 75 76 template<typename T> struct HashCompatible<T, T> : std::true_type {}; 77 78 template<typename Lhs, typename Rhs> 79 constexpr bool IsHashCompatible = HashCompatible<Lhs, Rhs>::value; 80 81 } 82 83 #endif // hash_hh_INCLUDED