ceptr
 All Data Structures Files Functions Variables Typedefs Macros Modules Pages
hashfn.c
1 // Paul Hsieh's hash taken from http://burtleburtle.net/bob/hash/doobs.html
2 
3 #include "hashfn.h"
4 #include <stdio.h>
5 #undef get16bits
6 #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
7 #define get16bits(d) (*((const uint16_t *) (d)))
8 #endif
9 
10 #if !defined (get16bits)
11 #define get16bits(d) ((((const uint8_t *)(d))[1] << UINT32_C(8))\
12  +((const uint8_t *)(d))[0])
13 #endif
14 
15 uint32_t hashfn(const char * data, int len) {
16 uint32_t hash = len, tmp;
17 int rem;
18 
19  if (len <= 0 || data == NULL) return 0;
20 
21  rem = len & 3;
22  len >>= 2;
23 
24  /* Main loop */
25  for (;len > 0; len--) {
26  hash += get16bits (data);
27  tmp = (get16bits (data+2) << 11) ^ hash;
28  hash = (hash << 16) ^ tmp;
29  data += 2*sizeof (uint16_t);
30  hash += hash >> 11;
31  }
32 
33  /* Handle end cases */
34  switch (rem) {
35  case 3: hash += get16bits (data);
36  hash ^= hash << 16;
37  hash ^= data[sizeof (uint16_t)] << 18;
38  hash += hash >> 11;
39  break;
40  case 2: hash += get16bits (data);
41  hash ^= hash << 11;
42  hash += hash >> 17;
43  break;
44  case 1: hash += *data;
45  hash ^= hash << 10;
46  hash += hash >> 1;
47  }
48 
49  /* Force "avalanching" of final 127 bits */
50  hash ^= hash << 3;
51  hash += hash >> 5;
52  hash ^= hash << 4;
53  hash += hash >> 17;
54  hash ^= hash << 25;
55  hash += hash >> 6;
56 
57  return hash;
58 }