hash.hpp 898 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #pragma once
  2. #include <bit>
  3. #include <utility>
  4. #include <stdint.h>
  5. #include <types/path.hpp>
  6. #include <types/types.h>
  7. namespace types {
  8. // taken from linux
  9. constexpr uint64_t GOLDEN_RATIO_64 = 0x61C8864680B583EBull;
  10. using hash_t = std::size_t;
  11. constexpr hash_t hash(uint64_t val, int bits) {
  12. // higher bits are more random
  13. return (val * GOLDEN_RATIO_64) >> (64 - bits);
  14. }
  15. inline hash_t hash_ptr(const void* p, int bits) {
  16. return hash(std::bit_cast<uintptr_t>(p), bits);
  17. }
  18. inline hash_t hash_str(const char* str, int bits) {
  19. constexpr hash_t seed = 131;
  20. hash_t tmp = 0;
  21. while (*str)
  22. tmp = tmp * seed + (*str++);
  23. return hash(tmp, bits);
  24. };
  25. inline hash_t hash_str(string_view str, int bits) {
  26. constexpr hash_t seed = 131;
  27. hash_t tmp = 0;
  28. for (auto c : str)
  29. tmp = tmp * seed + c;
  30. return hash(tmp, bits);
  31. };
  32. } // namespace types