diff options
author | Dominick Allen <djallen@librehumanitas.org> | 2025-03-30 23:08:43 -0500 |
---|---|---|
committer | Dominick Allen <djallen@librehumanitas.org> | 2025-03-30 23:08:43 -0500 |
commit | cb9fa588ba8144fcdd52ba4b83d69d93fb18066f (patch) | |
tree | 214574ca68c1551ec76e7fbb9e0263793180231d /include/fud_hash.hpp | |
parent | 1d357adfa19725ee69fb267a363f1fd217b1272f (diff) |
Add hash map.
Diffstat (limited to 'include/fud_hash.hpp')
-rw-r--r-- | include/fud_hash.hpp | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/include/fud_hash.hpp b/include/fud_hash.hpp new file mode 100644 index 0000000..57b5619 --- /dev/null +++ b/include/fud_hash.hpp @@ -0,0 +1,77 @@ +/* + * 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); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return djb2(reinterpret_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 |