krot

SuperFastHash

Aug 24th, 2016
72
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdint.h>
  2.  
  3. #undef get16bits
  4. #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
  5.   || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
  6. #define get16bits(d) (*((const uint16_t *) (d)))
  7. #endif
  8. #if !defined (get16bits)
  9. #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
  10.                        +(uint32_t)(((const uint8_t *)(d))[0]) )
  11. #endif
  12. uint32_t SuperFastHash (const char * data, int len) {
  13. uint32_t hash = len, tmp;
  14. int rem;
  15.     if (len <= 0 || data == NULL) return 0;
  16.     rem = len & 3;
  17.     len >>= 2;
  18.     /* Main loop */
  19.     for (;len > 0; len--) {
  20.         hash  += get16bits (data);
  21.         tmp    = (get16bits (data+2) << 11) ^ hash;
  22.         hash   = (hash << 16) ^ tmp;
  23.         data  += 2*sizeof (uint16_t);
  24.         hash  += hash >> 11;
  25.     }
  26.     /* Handle end cases */
  27.     switch (rem) {
  28.         case 3: hash += get16bits (data);
  29.                 hash ^= hash << 16;
  30.                 hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
  31.                 hash += hash >> 11;
  32.                 break;
  33.         case 2: hash += get16bits (data);
  34.                 hash ^= hash << 11;
  35.                 hash += hash >> 17;
  36.                 break;
  37.         case 1: hash += (signed char)*data;
  38.                 hash ^= hash << 10;
  39.                 hash += hash >> 1;
  40.     }
  41.     /* Force "avalanching" of final 127 bits */
  42.     hash ^= hash << 3;
  43.     hash += hash >> 5;
  44.     hash ^= hash << 4;
  45.     hash += hash >> 17;
  46.     hash ^= hash << 25;
  47.     hash += hash >> 6;
  48.     return hash;
  49. }
RAW Paste Data