Skip to content

Instantly share code, notes, and snippets.

@morrisonlevi
Last active November 14, 2015 23:03
Show Gist options
  • Save morrisonlevi/bdd123a9a1cf67c13ec8 to your computer and use it in GitHub Desktop.
Save morrisonlevi/bdd123a9a1cf67c13ec8 to your computer and use it in GitHub Desktop.
A compile-time Bernstein hash example using constexpr (c++11 or above).
#include <cstddef>
#include <iostream>
constexpr std::size_t bernstein_hash(char const *s, std::size_t size, std::size_t value = 5381) {
return size ? bernstein_hash(s + 1, size - 1, 33 * value + *s) : value;
}
struct symbol {
std::size_t const len;
std::size_t const hash;
char const * const str;
template<std::size_t N>
constexpr symbol(char const (&s)[N]) noexcept : len{N - 1}, hash{bernstein_hash(s, len)}, str{s} {}
};
int main() {
symbol name("Bernstein");
std::cout << name.str << std::endl;
std::cout << name.hash << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment