hash_combine.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (c) 2022 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef SOURCE_UTIL_HASH_COMBINE_H_
  15. #define SOURCE_UTIL_HASH_COMBINE_H_
  16. #include <cstddef>
  17. #include <functional>
  18. #include <vector>
  19. namespace spvtools {
  20. namespace utils {
  21. // Helpers for incrementally computing hashes.
  22. // For reference, see
  23. // http://open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3876.pdf
  24. template <typename T>
  25. inline size_t hash_combine(std::size_t seed, const T& val) {
  26. return seed ^ (std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
  27. }
  28. template <typename T>
  29. inline size_t hash_combine(std::size_t hash, const std::vector<T>& vals) {
  30. for (const T& val : vals) {
  31. hash = hash_combine(hash, val);
  32. }
  33. return hash;
  34. }
  35. inline size_t hash_combine(std::size_t hash) { return hash; }
  36. template <typename T, typename... Types>
  37. inline size_t hash_combine(std::size_t hash, const T& val,
  38. const Types&... args) {
  39. return hash_combine(hash_combine(hash, val), args...);
  40. }
  41. } // namespace utils
  42. } // namespace spvtools
  43. #endif // SOURCE_UTIL_HASH_COMBINE_H_