From 9e3a66d5bf58d01653b57189f86bcf68988a4786 Mon Sep 17 00:00:00 2001 From: Max Kellermann <mk@cm4all.com> Date: Mon, 6 May 2024 23:04:41 +0200 Subject: [PATCH] util/djb_hash: make inline and constexpr Allows calculating hashes at compile time. --- src/util/djb_hash.cxx | 40 ---------------------------------------- src/util/djb_hash.hxx | 37 ++++++++++++++++++++++++++++++------- src/util/meson.build | 1 - 3 files changed, 30 insertions(+), 48 deletions(-) delete mode 100644 src/util/djb_hash.cxx diff --git a/src/util/djb_hash.cxx b/src/util/djb_hash.cxx deleted file mode 100644 index 559a692dd..000000000 --- a/src/util/djb_hash.cxx +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: BSD-2-Clause -// Copyright CM4all GmbH -// author: Max Kellermann <mk@cm4all.com> - -#include "djb_hash.hxx" - -#include <cassert> - -[[gnu::always_inline]] [[gnu::hot]] -static constexpr std::size_t -djb_hash_update(std::size_t hash, std::byte b) noexcept -{ - return (hash * 33) ^ static_cast<std::size_t>(b); -} - -[[gnu::hot]] -std::size_t -djb_hash(std::span<const std::byte> src, std::size_t init) noexcept -{ - std::size_t hash = init; - - for (const auto i : src) - hash = djb_hash_update(hash, i); - - return hash; -} - -[[gnu::hot]] -std::size_t -djb_hash_string(const char *p, std::size_t init) noexcept -{ - assert(p != nullptr); - - std::size_t hash = init; - - while (*p != 0) - hash = djb_hash_update(hash, static_cast<std::byte>(*p++)); - - return hash; -} diff --git a/src/util/djb_hash.hxx b/src/util/djb_hash.hxx index 6eff57013..bbf732a9f 100644 --- a/src/util/djb_hash.hxx +++ b/src/util/djb_hash.hxx @@ -14,12 +14,35 @@ static constexpr std::size_t DJB_HASH_INIT = 5381; -[[gnu::pure]] -std::size_t -djb_hash(std::span<const std::byte> src, - std::size_t init=DJB_HASH_INIT) noexcept; +[[nodiscard]] [[gnu::always_inline]] [[gnu::hot]] +constexpr std::size_t +djb_hash_update(std::size_t hash, std::byte b) noexcept +{ + return (hash * 33) ^ static_cast<std::size_t>(b); +} -[[gnu::pure]] -std::size_t +[[nodiscard]] [[gnu::hot]] +constexpr std::size_t +djb_hash(std::span<const std::byte> src, + std::size_t init=DJB_HASH_INIT) noexcept +{ + std::size_t hash = init; + + for (const auto i : src) + hash = djb_hash_update(hash, i); + + return hash; +} + +[[nodiscard]] [[gnu::hot]] +constexpr std::size_t djb_hash_string(const char *p, - std::size_t init=DJB_HASH_INIT) noexcept; + std::size_t init=DJB_HASH_INIT) noexcept +{ + std::size_t hash = init; + + while (*p != 0) + hash = djb_hash_update(hash, static_cast<std::byte>(*p++)); + + return hash; +} diff --git a/src/util/meson.build b/src/util/meson.build index 4d69809d0..7ada1dd36 100644 --- a/src/util/meson.build +++ b/src/util/meson.build @@ -23,7 +23,6 @@ util = static_library( 'ByteReverse.cxx', 'format.c', 'BitReverse.cxx', - 'djb_hash.cxx', 'Serial.cxx', include_directories: inc, )