]> git.ozlabs.org Git - ccan/blob - ccan/tdb/hash.c
tdb: add Bob Jenkins lookup3 hash as helper hash.
[ccan] / ccan / tdb / hash.c
1 #include "tdb_private.h"
2
3 /* This is based on the hash algorithm from gdbm */
4 unsigned int tdb_old_hash(TDB_DATA *key)
5 {
6         uint32_t value; /* Used to compute the hash value.  */
7         uint32_t   i;   /* Used to cycle through random values. */
8
9         /* Set the initial value from the key size. */
10         for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
11                 value = (value + (key->dptr[i] << (i*5 % 24)));
12
13         return (1103515243 * value + 12345);  
14 }
15
16 #if HAVE_LITTLE_ENDIAN
17 # define HASH_LITTLE_ENDIAN 1
18 # define HASH_BIG_ENDIAN 0
19 #elif HAVE_BIG_ENDIAN
20 # define HASH_LITTLE_ENDIAN 0
21 # define HASH_BIG_ENDIAN 1
22 #else
23 # error Unknown endian
24 #endif
25
26 /*
27 -------------------------------------------------------------------------------
28 lookup3.c, by Bob Jenkins, May 2006, Public Domain.
29
30 These are functions for producing 32-bit hashes for hash table lookup.
31 hash_word(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() 
32 are externally useful functions.  Routines to test the hash are included 
33 if SELF_TEST is defined.  You can use this free for any purpose.  It's in
34 the public domain.  It has no warranty.
35
36 You probably want to use hashlittle().  hashlittle() and hashbig()
37 hash byte arrays.  hashlittle() is is faster than hashbig() on
38 little-endian machines.  Intel and AMD are little-endian machines.
39 On second thought, you probably want hashlittle2(), which is identical to
40 hashlittle() except it returns two 32-bit hashes for the price of one.  
41 You could implement hashbig2() if you wanted but I haven't bothered here.
42
43 If you want to find a hash of, say, exactly 7 integers, do
44   a = i1;  b = i2;  c = i3;
45   mix(a,b,c);
46   a += i4; b += i5; c += i6;
47   mix(a,b,c);
48   a += i7;
49   final(a,b,c);
50 then use c as the hash value.  If you have a variable length array of
51 4-byte integers to hash, use hash_word().  If you have a byte array (like
52 a character string), use hashlittle().  If you have several byte arrays, or
53 a mix of things, see the comments above hashlittle().  
54
55 Why is this so big?  I read 12 bytes at a time into 3 4-byte integers, 
56 then mix those integers.  This is fast (you can do a lot more thorough
57 mixing with 12*3 instructions on 3 integers than you can with 3 instructions
58 on 1 byte), but shoehorning those bytes into integers efficiently is messy.
59 */
60
61 #define hashsize(n) ((uint32_t)1<<(n))
62 #define hashmask(n) (hashsize(n)-1)
63 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
64
65 /*
66 -------------------------------------------------------------------------------
67 mix -- mix 3 32-bit values reversibly.
68
69 This is reversible, so any information in (a,b,c) before mix() is
70 still in (a,b,c) after mix().
71
72 If four pairs of (a,b,c) inputs are run through mix(), or through
73 mix() in reverse, there are at least 32 bits of the output that
74 are sometimes the same for one pair and different for another pair.
75 This was tested for:
76 * pairs that differed by one bit, by two bits, in any combination
77   of top bits of (a,b,c), or in any combination of bottom bits of
78   (a,b,c).
79 * "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
80   the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
81   is commonly produced by subtraction) look like a single 1-bit
82   difference.
83 * the base values were pseudorandom, all zero but one bit set, or 
84   all zero plus a counter that starts at zero.
85
86 Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
87 satisfy this are
88     4  6  8 16 19  4
89     9 15  3 18 27 15
90    14  9  3  7 17  3
91 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
92 for "differ" defined as + with a one-bit base and a two-bit delta.  I
93 used http://burtleburtle.net/bob/hash/avalanche.html to choose 
94 the operations, constants, and arrangements of the variables.
95
96 This does not achieve avalanche.  There are input bits of (a,b,c)
97 that fail to affect some output bits of (a,b,c), especially of a.  The
98 most thoroughly mixed value is c, but it doesn't really even achieve
99 avalanche in c.
100
101 This allows some parallelism.  Read-after-writes are good at doubling
102 the number of bits affected, so the goal of mixing pulls in the opposite
103 direction as the goal of parallelism.  I did what I could.  Rotates
104 seem to cost as much as shifts on every machine I could lay my hands
105 on, and rotates are much kinder to the top and bottom bits, so I used
106 rotates.
107 -------------------------------------------------------------------------------
108 */
109 #define mix(a,b,c) \
110 { \
111   a -= c;  a ^= rot(c, 4);  c += b; \
112   b -= a;  b ^= rot(a, 6);  a += c; \
113   c -= b;  c ^= rot(b, 8);  b += a; \
114   a -= c;  a ^= rot(c,16);  c += b; \
115   b -= a;  b ^= rot(a,19);  a += c; \
116   c -= b;  c ^= rot(b, 4);  b += a; \
117 }
118
119 /*
120 -------------------------------------------------------------------------------
121 final -- final mixing of 3 32-bit values (a,b,c) into c
122
123 Pairs of (a,b,c) values differing in only a few bits will usually
124 produce values of c that look totally different.  This was tested for
125 * pairs that differed by one bit, by two bits, in any combination
126   of top bits of (a,b,c), or in any combination of bottom bits of
127   (a,b,c).
128 * "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
129   the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
130   is commonly produced by subtraction) look like a single 1-bit
131   difference.
132 * the base values were pseudorandom, all zero but one bit set, or 
133   all zero plus a counter that starts at zero.
134
135 These constants passed:
136  14 11 25 16 4 14 24
137  12 14 25 16 4 14 24
138 and these came close:
139   4  8 15 26 3 22 24
140  10  8 15 26 3 22 24
141  11  8 15 26 3 22 24
142 -------------------------------------------------------------------------------
143 */
144 #define final(a,b,c) \
145 { \
146   c ^= b; c -= rot(b,14); \
147   a ^= c; a -= rot(c,11); \
148   b ^= a; b -= rot(a,25); \
149   c ^= b; c -= rot(b,16); \
150   a ^= c; a -= rot(c,4);  \
151   b ^= a; b -= rot(a,14); \
152   c ^= b; c -= rot(b,24); \
153 }
154
155
156 /*
157 -------------------------------------------------------------------------------
158 hashlittle() -- hash a variable-length key into a 32-bit value
159   k       : the key (the unaligned variable-length array of bytes)
160   length  : the length of the key, counting by bytes
161   val2    : IN: can be any 4-byte value OUT: second 32 bit hash.
162 Returns a 32-bit value.  Every bit of the key affects every bit of
163 the return value.  Two keys differing by one or two bits will have
164 totally different hash values.  Note that the return value is better
165 mixed than val2, so use that first.
166
167 The best hash table sizes are powers of 2.  There is no need to do
168 mod a prime (mod is sooo slow!).  If you need less than 32 bits,
169 use a bitmask.  For example, if you need only 10 bits, do
170   h = (h & hashmask(10));
171 In which case, the hash table should have hashsize(10) elements.
172
173 If you are hashing n strings (uint8_t **)k, do it like this:
174   for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
175
176 By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
177 code any way you wish, private, educational, or commercial.  It's free.
178
179 Use for hash table lookup, or anything where one collision in 2^^32 is
180 acceptable.  Do NOT use for cryptographic purposes.
181 -------------------------------------------------------------------------------
182 */
183
184 static uint32_t hashlittle( const void *key, size_t length )
185 {
186   uint32_t a,b,c;                                          /* internal state */
187   union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */
188
189   /* Set up the internal state */
190   a = b = c = 0xdeadbeef + ((uint32_t)length);
191
192   u.ptr = key;
193   if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
194     const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
195 #ifdef VALGRIND
196     const uint8_t  *k8;
197 #endif
198
199     /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
200     while (length > 12)
201     {
202       a += k[0];
203       b += k[1];
204       c += k[2];
205       mix(a,b,c);
206       length -= 12;
207       k += 3;
208     }
209
210     /*----------------------------- handle the last (probably partial) block */
211     /* 
212      * "k[2]&0xffffff" actually reads beyond the end of the string, but
213      * then masks off the part it's not allowed to read.  Because the
214      * string is aligned, the masked-off tail is in the same word as the
215      * rest of the string.  Every machine with memory protection I've seen
216      * does it on word boundaries, so is OK with this.  But VALGRIND will
217      * still catch it and complain.  The masking trick does make the hash
218      * noticably faster for short strings (like English words).
219      */
220 #ifndef VALGRIND
221
222     switch(length)
223     {
224     case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
225     case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
226     case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
227     case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
228     case 8 : b+=k[1]; a+=k[0]; break;
229     case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
230     case 6 : b+=k[1]&0xffff; a+=k[0]; break;
231     case 5 : b+=k[1]&0xff; a+=k[0]; break;
232     case 4 : a+=k[0]; break;
233     case 3 : a+=k[0]&0xffffff; break;
234     case 2 : a+=k[0]&0xffff; break;
235     case 1 : a+=k[0]&0xff; break;
236     case 0 : return c;              /* zero length strings require no mixing */
237     }
238
239 #else /* make valgrind happy */
240
241     k8 = (const uint8_t *)k;
242     switch(length)
243     {
244     case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
245     case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
246     case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
247     case 9 : c+=k8[8];                   /* fall through */
248     case 8 : b+=k[1]; a+=k[0]; break;
249     case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
250     case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
251     case 5 : b+=k8[4];                   /* fall through */
252     case 4 : a+=k[0]; break;
253     case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
254     case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
255     case 1 : a+=k8[0]; break;
256     case 0 : return c;
257     }
258
259 #endif /* !valgrind */
260
261   } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
262     const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
263     const uint8_t  *k8;
264
265     /*--------------- all but last block: aligned reads and different mixing */
266     while (length > 12)
267     {
268       a += k[0] + (((uint32_t)k[1])<<16);
269       b += k[2] + (((uint32_t)k[3])<<16);
270       c += k[4] + (((uint32_t)k[5])<<16);
271       mix(a,b,c);
272       length -= 12;
273       k += 6;
274     }
275
276     /*----------------------------- handle the last (probably partial) block */
277     k8 = (const uint8_t *)k;
278     switch(length)
279     {
280     case 12: c+=k[4]+(((uint32_t)k[5])<<16);
281              b+=k[2]+(((uint32_t)k[3])<<16);
282              a+=k[0]+(((uint32_t)k[1])<<16);
283              break;
284     case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
285     case 10: c+=k[4];
286              b+=k[2]+(((uint32_t)k[3])<<16);
287              a+=k[0]+(((uint32_t)k[1])<<16);
288              break;
289     case 9 : c+=k8[8];                      /* fall through */
290     case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
291              a+=k[0]+(((uint32_t)k[1])<<16);
292              break;
293     case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
294     case 6 : b+=k[2];
295              a+=k[0]+(((uint32_t)k[1])<<16);
296              break;
297     case 5 : b+=k8[4];                      /* fall through */
298     case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
299              break;
300     case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
301     case 2 : a+=k[0];
302              break;
303     case 1 : a+=k8[0];
304              break;
305     case 0 : return c;                     /* zero length requires no mixing */
306     }
307
308   } else {                        /* need to read the key one byte at a time */
309     const uint8_t *k = (const uint8_t *)key;
310
311     /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
312     while (length > 12)
313     {
314       a += k[0];
315       a += ((uint32_t)k[1])<<8;
316       a += ((uint32_t)k[2])<<16;
317       a += ((uint32_t)k[3])<<24;
318       b += k[4];
319       b += ((uint32_t)k[5])<<8;
320       b += ((uint32_t)k[6])<<16;
321       b += ((uint32_t)k[7])<<24;
322       c += k[8];
323       c += ((uint32_t)k[9])<<8;
324       c += ((uint32_t)k[10])<<16;
325       c += ((uint32_t)k[11])<<24;
326       mix(a,b,c);
327       length -= 12;
328       k += 12;
329     }
330
331     /*-------------------------------- last block: affect all 32 bits of (c) */
332     switch(length)                   /* all the case statements fall through */
333     {
334     case 12: c+=((uint32_t)k[11])<<24;
335     case 11: c+=((uint32_t)k[10])<<16;
336     case 10: c+=((uint32_t)k[9])<<8;
337     case 9 : c+=k[8];
338     case 8 : b+=((uint32_t)k[7])<<24;
339     case 7 : b+=((uint32_t)k[6])<<16;
340     case 6 : b+=((uint32_t)k[5])<<8;
341     case 5 : b+=k[4];
342     case 4 : a+=((uint32_t)k[3])<<24;
343     case 3 : a+=((uint32_t)k[2])<<16;
344     case 2 : a+=((uint32_t)k[1])<<8;
345     case 1 : a+=k[0];
346              break;
347     case 0 : return c;
348     }
349   }
350
351   final(a,b,c);
352   return c;
353 }
354
355 unsigned int tdb_jenkins_hash(TDB_DATA *key)
356 {
357         return hashlittle(key->dptr, key->dsize);
358 }