HashFunctions.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Types.h>
  8. constexpr unsigned int_hash(u32 key)
  9. {
  10. key += ~(key << 15);
  11. key ^= (key >> 10);
  12. key += (key << 3);
  13. key ^= (key >> 6);
  14. key += ~(key << 11);
  15. key ^= (key >> 16);
  16. return key;
  17. }
  18. constexpr unsigned double_hash(u32 key)
  19. {
  20. const unsigned magic = 0xBA5EDB01;
  21. if (key == magic)
  22. return 0u;
  23. if (key == 0u)
  24. key = magic;
  25. key ^= key << 13;
  26. key ^= key >> 17;
  27. key ^= key << 5;
  28. return key;
  29. }
  30. constexpr unsigned pair_int_hash(u32 key1, u32 key2)
  31. {
  32. return int_hash((int_hash(key1) * 209) ^ (int_hash(key2 * 413)));
  33. }
  34. constexpr unsigned u64_hash(u64 key)
  35. {
  36. u32 first = key & 0xFFFFFFFF;
  37. u32 last = key >> 32;
  38. return pair_int_hash(first, last);
  39. }
  40. constexpr unsigned ptr_hash(FlatPtr ptr)
  41. {
  42. if constexpr (sizeof(ptr) == 8)
  43. return u64_hash(ptr);
  44. else
  45. return int_hash(ptr);
  46. }
  47. inline unsigned ptr_hash(const void* ptr)
  48. {
  49. return ptr_hash(FlatPtr(ptr));
  50. }