hashmap.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2022-08-01 GuEe-GUI first version
  9. */
  10. #ifndef __UTIL_HASHMAP_H__
  11. #define __UTIL_HASHMAP_H__
  12. #include <rtdef.h>
  13. /*
  14. * http://www.citi.umich.edu/techreports/reports/citi-tr-00-1.pdf
  15. *
  16. * GoldenRatio = ~(Math.pow(2, 32) / ((Math.sqrt(5) - 1) / 2)) + 1
  17. */
  18. #define RT_HASHMAP_GOLDEN_RATIO_32 0x61C88647
  19. #define RT_HASHMAP_GOLDEN_RATIO_64 0X61C8864680B583EBULL
  20. rt_inline rt_uint32_t rt_hashmap_32(rt_uint32_t val, rt_uint32_t bits)
  21. {
  22. /* High bits are more random, so use them. */
  23. return (val * RT_HASHMAP_GOLDEN_RATIO_32) >> (32 - bits);
  24. }
  25. rt_inline rt_uint32_t rt_hashmap_64(rt_uint64_t val, rt_uint32_t bits)
  26. {
  27. #ifdef ARCH_CPU_64BIT
  28. /* 64x64-bit multiply is efficient on all 64-bit processors */
  29. return val * RT_HASHMAP_GOLDEN_RATIO_64 >> (64 - bits);
  30. #else
  31. /* Hash 64 bits using only 32x32-bit multiply. */
  32. return rt_hashmap_32((rt_uint32_t)val ^ ((val >> 32) * RT_HASHMAP_GOLDEN_RATIO_32), bits);
  33. #endif
  34. }
  35. #endif /* __UTIL_HASHMAP_H__ */