HashCombine.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. namespace JPH {
  5. inline void hash_combine(std::size_t &ioSeed)
  6. {
  7. }
  8. /// Hash combiner to use a custom struct in an unordered map or set
  9. /// Taken from: https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x
  10. ///
  11. /// Usage:
  12. ///
  13. /// struct SomeHashKey
  14. /// {
  15. /// std::string key1;
  16. /// std::string key2;
  17. /// bool key3;
  18. /// };
  19. ///
  20. /// JPH_MAKE_HASHABLE(SomeHashKey, t.key1, t.key2, t.key3)
  21. template <typename T, typename... Rest>
  22. inline void hash_combine(std::size_t &ioSeed, const T &inValue, Rest... inRest)
  23. {
  24. std::hash<T> hasher;
  25. ioSeed ^= hasher(inValue) + 0x9e3779b9 + (ioSeed << 6) + (ioSeed >> 2);
  26. hash_combine(ioSeed, inRest...);
  27. }
  28. } // JPH
  29. #define JPH_MAKE_HASH_STRUCT(type, name, ...) \
  30. struct [[nodiscard]] name \
  31. { \
  32. std::size_t operator()(const type &t) const \
  33. { \
  34. std::size_t ret = 0; \
  35. ::JPH::hash_combine(ret, __VA_ARGS__); \
  36. return ret; \
  37. } \
  38. };
  39. #define JPH_MAKE_HASHABLE(type, ...) \
  40. namespace std \
  41. { \
  42. template<> \
  43. JPH_MAKE_HASH_STRUCT(type, hash<type>, __VA_ARGS__) \
  44. }