hash.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // This code is in the public domain -- Ignacio Castaño <[email protected]>
  2. #pragma once
  3. #ifndef NV_CORE_HASH_H
  4. #define NV_CORE_HASH_H
  5. #include "nvcore.h"
  6. namespace nv
  7. {
  8. inline uint sdbmHash(const void * data_in, uint size, uint h = 5381)
  9. {
  10. const uint8 * data = (const uint8 *) data_in;
  11. uint i = 0;
  12. while (i < size) {
  13. h = (h << 16) + (h << 6) - h + (uint) data[i++];
  14. }
  15. return h;
  16. }
  17. // Note that this hash does not handle NaN properly.
  18. inline uint sdbmFloatHash(const float * f, uint count, uint h = 5381)
  19. {
  20. for (uint i = 0; i < count; i++) {
  21. //nvDebugCheck(nv::isFinite(*f));
  22. union { float f; uint32 i; } x = { f[i] };
  23. if (x.i == 0x80000000) x.i = 0;
  24. h = sdbmHash(&x, 4, h);
  25. }
  26. return h;
  27. }
  28. template <typename T>
  29. inline uint hash(const T & t, uint h = 5381)
  30. {
  31. return sdbmHash(&t, sizeof(T), h);
  32. }
  33. template <>
  34. inline uint hash(const float & f, uint h)
  35. {
  36. return sdbmFloatHash(&f, 1, h);
  37. }
  38. // Functors for hash table:
  39. template <typename Key> struct Hash
  40. {
  41. uint operator()(const Key & k) const {
  42. return hash(k);
  43. }
  44. };
  45. template <typename Key> struct Equal
  46. {
  47. bool operator()(const Key & k0, const Key & k1) const {
  48. return k0 == k1;
  49. }
  50. };
  51. // @@ Move to Utils.h?
  52. template <typename T1, typename T2>
  53. struct Pair {
  54. T1 first;
  55. T2 second;
  56. };
  57. template <typename T1, typename T2>
  58. bool operator==(const Pair<T1,T2> & p0, const Pair<T1,T2> & p1) {
  59. return p0.first == p1.first && p0.second == p1.second;
  60. }
  61. template <typename T1, typename T2>
  62. uint hash(const Pair<T1,T2> & p, uint h = 5381) {
  63. return hash(p.second, hash(p.first));
  64. }
  65. } // nv namespace
  66. #endif // NV_CORE_HASH_H