Rewrite by making the hashByte function separate

This commit is contained in:
Jean Pierre Cimalando 2020-10-21 00:14:52 +02:00
parent 16f34da8bc
commit 1c0d597d01

View file

@ -12,6 +12,7 @@
#pragma once
#include "absl/strings/string_view.h"
#include <cstdint>
/**
* @brief Removes the whitespace on a string_view in place
@ -45,6 +46,18 @@ inline absl::string_view trim(absl::string_view s)
constexpr uint64_t Fnv1aBasis = 0x811C9DC5;
constexpr uint64_t Fnv1aPrime = 0x01000193;
/**
* @brief Hash a single byte.
*
* @param s the input string to be hashed
* @param h the hashing seed to use
* @return uint64_t
*/
constexpr uint64_t hashByte(uint8_t byte, uint64_t h = Fnv1aBasis)
{
return (h ^ byte) * Fnv1aPrime;
}
/**
* @brief Compile-time hashing function to be used mostly with switch/case statements.
*
@ -56,7 +69,7 @@ constexpr uint64_t Fnv1aPrime = 0x01000193;
*/
constexpr uint64_t hash(absl::string_view s, uint64_t h = Fnv1aBasis)
{
return (s.length() == 0) ? h : hash( { s.data() + 1, s.length() - 1 }, (h ^ static_cast<unsigned char>(s.front())) * Fnv1aPrime );
return (s.length() == 0) ? h : hash({ s.data() + 1, s.length() - 1 }, hashByte(s.front(), h));
}
/**
@ -73,7 +86,7 @@ constexpr uint64_t hashNoAmpersand(absl::string_view s, uint64_t h = Fnv1aBasis)
return (s.length() == 0) ? h : (
(s.front() == '&')
? hashNoAmpersand( { s.data() + 1, s.length() - 1 }, h )
: hashNoAmpersand( { s.data() + 1, s.length() - 1 }, (h ^ static_cast<unsigned char>(s.front())) * Fnv1aPrime )
: hashNoAmpersand( { s.data() + 1, s.length() - 1 }, hashByte(s.front(), h) )
);
}