blob: a4721718e287f18f137bbd50023118a68c3bffd6 (
plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
/*
* libfud
* Copyright 2025 Dominick Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FUD_HASH_HPP
#define FUD_HASH_HPP
#include "fud_string.hpp"
#include "fud_string_view.hpp"
#include "fud_utf8.hpp"
#include <type_traits>
/*
namespace fud {
template <typename Key>
concept Hashable = requires(Key key) {
{ sink.drain(source) } -> std::same_as<DrainResult>;
};
} // namespace fud
*/
namespace fud::detail {
constexpr uint64_t roundToNearest2(uint64_t inputValue) noexcept
{
uint64_t outputValue = inputValue - 1;
constexpr uint8_t max2PowerShift = 32;
for (uint8_t shift = 1; shift <= max2PowerShift; shift *= 2) {
outputValue |= outputValue >> shift;
}
outputValue++;
return outputValue;
}
/** \brief The djb2 algorithm by Dan Bernstein. See http://www.cse.yorku.ca/~oz/hash.html
*
* If passed a null pointer for data, returns the initial hash value.
*/
size_t djb2(const utf8* data, size_t length);
template <typename T>
struct DefaultHash {
static_assert(std::is_integral_v<T> || std::is_enum_v<T>);
size_t operator()(const T& value, size_t seed) const
{
static_cast<void>(seed);
return djb2(std::bit_cast<const utf8*>(&value), sizeof(value));
}
};
template <>
struct DefaultHash<String> {
size_t operator()(const String& value, size_t seed) const;
};
template <>
struct DefaultHash<StringView> {
size_t operator()(const StringView& value, size_t seed) const;
};
} // namespace fud::detail
#endif
|