Skip to content

Commit

Permalink
Merge pull request #512 from jpcima/fnv1a
Browse files Browse the repository at this point in the history
Fix an implementation error of FNV-1a
  • Loading branch information
jpcima authored Oct 20, 2020
2 parents 11fd2f3 + 1c0d597 commit 3cc53a9
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/sfizz/StringViewHelpers.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#pragma once
#include "absl/strings/string_view.h"
#include <cstdint>

/**
* @brief Removes the whitespace on a string_view in place
Expand Down Expand Up @@ -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.
*
Expand All @@ -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 ^ s.front()) * Fnv1aPrime );
return (s.length() == 0) ? h : hash({ s.data() + 1, s.length() - 1 }, hashByte(s.front(), h));
}

/**
Expand All @@ -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 ^ s.front()) * Fnv1aPrime )
: hashNoAmpersand( { s.data() + 1, s.length() - 1 }, hashByte(s.front(), h) )
);
}

Expand Down

0 comments on commit 3cc53a9

Please sign in to comment.