Skip to content

Instantly share code, notes, and snippets.

@donny-dont
Created October 28, 2011 07:40
Show Gist options
  • Save donny-dont/1321819 to your computer and use it in GitHub Desktop.
Save donny-dont/1321819 to your computer and use it in GitHub Desktop.
Templated hash
#include <cstdint>
#include <cstdio>
#define INLINE __forceinline
template <typename HashFunction>
class StringHash
{
public:
template <std::size_t N>
INLINE StringHash(const char (&value)[N])
: _hash(HashFunction::hash<N>(value))
{ }
INLINE std::uint32_t getHash() { return _hash; }
private:
std::uint32_t _hash;
} ;
struct HashFNV1a
{
template <std::size_t N>
INLINE static std::uint32_t hash(const char (&value)[N])
{
return (hash<N-1>((const char(&)[N-1])value)^ value[N-1]) * 16777619u;
}
template <>
INLINE static std::uint32_t hash<1>(const char (&value)[1])
{
return (2166136261u^ value[0]) * 16777619u;
}
} ;
int main()
{
typedef StringHash<HashFNV1a> StringHashFNV1a;
printf("Hash test: %d", StringHashFNV1a("").getHash());
/*
push 84696351 ; 050c5d1fH
push OFFSET ??_C@_0O@HFJMNHFL@Hash?5test?3?5?$CFd?$AA@
call esi
*/
printf("Hash test: %d", StringHashFNV1a("test").getHash());
/*
push -1440527489 ; aa234b7fH
push OFFSET ??_C@_0O@HFJMNHFL@Hash?5test?3?5?$CFd?$AA@
call esi
*/
printf("Hash test: %d", StringHashFNV1a("aLongerTest").getHash());
/*
push 1145903687 ; 444d1a47H
push OFFSET ??_C@_0O@HFJMNHFL@Hash?5test?3?5?$CFd?$AA@
call esi
*/
printf("Hash test: %d", StringHashFNV1a("aVeryLongTestWhichStillWorks").getHash());
/*
push 1839041337 ; 6d9d8b39H
push OFFSET ??_C@_0O@HFJMNHFL@Hash?5test?3?5?$CFd?$AA@
call esi
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment