hash.hpp 892 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. {
  13. // higher bits are more random
  14. return (val * GOLDEN_RATIO_64) >> (64 - bits);
  15. }
  16. inline hash_t hash_ptr(void* p, int bits)
  17. {
  18. return hash(std::bit_cast<uintptr_t>(p), bits);
  19. }
  20. inline hash_t hash_str(const char* str, int bits)
  21. {
  22. constexpr hash_t seed = 131;
  23. hash_t tmp = 0;
  24. while (*str)
  25. tmp = tmp * seed + (*str++);
  26. return hash(tmp, bits);
  27. };
  28. inline hash_t hash_str(string_view str, int bits)
  29. {
  30. constexpr hash_t seed = 131;
  31. hash_t tmp = 0;
  32. for (auto c : str)
  33. tmp = tmp * seed + c;
  34. return hash(tmp, bits);
  35. };
  36. } // namespace types