SuperFastHash.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "Platform.h"
  2. #include <stdio.h> // for NULL
  3. /* By Paul Hsieh (C) 2004, 2005. Covered under the Paul Hsieh derivative
  4. license. See:
  5. http://www.azillionmonkeys.com/qed/weblicense.html for license details.
  6. http://www.azillionmonkeys.com/qed/hash.html */
  7. /*
  8. #undef get16bits
  9. #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
  10. || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
  11. #define get16bits(d) (*((const uint16_t *) (d)))
  12. #endif
  13. #if !defined (get16bits)
  14. #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
  15. +(uint32_t)(((const uint8_t *)(d))[0]) )
  16. #endif
  17. */
  18. FORCE_INLINE uint16_t get16bits ( const void * p )
  19. {
  20. return *(const uint16_t*)p;
  21. }
  22. uint32_t SuperFastHash (const signed char * data, int len) {
  23. uint32_t hash = 0, tmp;
  24. int rem;
  25. if (len <= 0 || data == NULL) return 0;
  26. rem = len & 3;
  27. len >>= 2;
  28. /* Main loop */
  29. for (;len > 0; len--) {
  30. hash += get16bits (data);
  31. tmp = (get16bits (data+2) << 11) ^ hash;
  32. hash = (hash << 16) ^ tmp;
  33. data += 2*sizeof (uint16_t);
  34. hash += hash >> 11;
  35. }
  36. /* Handle end cases */
  37. switch (rem) {
  38. case 3: hash += get16bits (data);
  39. hash ^= hash << 16;
  40. hash ^= data[sizeof (uint16_t)] << 18;
  41. hash += hash >> 11;
  42. break;
  43. case 2: hash += get16bits (data);
  44. hash ^= hash << 11;
  45. hash += hash >> 17;
  46. break;
  47. case 1: hash += *data;
  48. hash ^= hash << 10;
  49. hash += hash >> 1;
  50. }
  51. /* Force "avalanching" of final 127 bits */
  52. hash ^= hash << 3;
  53. hash += hash >> 5;
  54. hash ^= hash << 4;
  55. hash += hash >> 17;
  56. hash ^= hash << 25;
  57. hash += hash >> 6;
  58. return hash;
  59. }
  60. void SuperFastHash ( const void * key, int len, uint32_t /*seed*/, void * out )
  61. {
  62. *(uint32_t*)out = SuperFastHash((const signed char*)key,len);
  63. }