1 /*
2 -------------------------------------------------------------------------------
3 lookup3.c, by Bob Jenkins, May 2006, Public Domain.
4 Original: http://burtleburtle.net/bob/c/lookup3.c
5 Modified by Russ Rew for adaption in netCDF.
6 - Make use of Paul Hsieh's pstdint.h, if stdint.h not available.
7 - Declare unused functions static to keep global namespace clean.
8 - Provide function hash_fast() that uses either hashlittle() or
9 hashbig(), depending on endianness.
10 - Because portability is more important than speed for netCDF use,
11 we define VALGRIND to skip "#ifndef VALGRIND" code, so reads of
12 strings don't access extra bytes after end of string. This may
13 slow it down enough to justify a simpler hash, but blame me, not
14 original author!
15
16 These are functions for producing 32-bit hashes for hash table lookup.
17 hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
18 are externally useful functions. Routines to test the hash are included
19 if SELF_TEST is defined. You can use this free for any purpose. It's in
20 the public domain. It has no warranty.
21
22 You probably want to use hashlittle(). hashlittle() and hashbig()
23 hash byte arrays. hashlittle() is is faster than hashbig() on
24 little-endian machines. Intel and AMD are little-endian machines.
25 On second thought, you probably want hashlittle2(), which is identical to
26 hashlittle() except it returns two 32-bit hashes for the price of one.
27 You could implement hashbig2() if you wanted but I haven't bothered here.
28
29 If you want to find a hash of, say, exactly 7 integers, do
30 a = i1; b = i2; c = i3;
31 mix(a,b,c);
32 a += i4; b += i5; c += i6;
33 mix(a,b,c);
34 a += i7;
35 final(a,b,c);
36 then use c as the hash value. If you have a variable length array of
37 4-byte integers to hash, use hashword(). If you have a byte array (like
38 a character string), use hashlittle(). If you have several byte arrays, or
39 a mix of things, see the comments above hashlittle().
40
41 Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
42 then mix those integers. This is fast (you can do a lot more thorough
43 mixing with 12*3 instructions on 3 integers than you can with 3 instructions
44 on 1 byte), but shoehorning those bytes into integers efficiently is messy.
45 -------------------------------------------------------------------------------
46 */
47 /* #define SELF_TEST 1 */
48
49 #if HAVE_CONFIG_H
50 #include <config.h>
51 #endif
52
53 #include <stdio.h> /* defines printf for tests */
54 #include <time.h> /* defines time_t for timings in the test */
55 #ifndef HAVE_STDINT_H
56 # include "pstdint.h" /* attempts to define uint32_t etc portably */
57 #else
58 # include <stdint.h>
59 #endif /* HAVE_STDINT_H */
60 #ifdef HAVE_SYS_PARAM_H
61 #include <sys/param.h> /* attempt to define endianness */
62 #endif /* HAVE_SYS_PARAM_H */
63 #ifdef linux
64 # include <endian.h> /* attempt to define endianness */
65 #endif
66
67 #define VALGRIND /* added by Russ Rew, for portability over speed */
68
69 #ifndef WORDS_BIGENDIAN /* from config.h */
70 #define HASH_LITTLE_ENDIAN 1
71 #define HASH_BIG_ENDIAN 0
72 #else
73 #define HASH_LITTLE_ENDIAN 0
74 #define HASH_BIG_ENDIAN 1
75 #endif
76
77 #define hashsize(n) ((uint32_t)1<<(n))
78 #define hashmask(n) (hashsize(n)-1)
79 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
80
81 /*
82 -------------------------------------------------------------------------------
83 mix -- mix 3 32-bit values reversibly.
84
85 This is reversible, so any information in (a,b,c) before mix() is
86 still in (a,b,c) after mix().
87
88 If four pairs of (a,b,c) inputs are run through mix(), or through
89 mix() in reverse, there are at least 32 bits of the output that
90 are sometimes the same for one pair and different for another pair.
91 This was tested for:
92 * pairs that differed by one bit, by two bits, in any combination
93 of top bits of (a,b,c), or in any combination of bottom bits of
94 (a,b,c).
95 * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
96 the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
97 is commonly produced by subtraction) look like a single 1-bit
98 difference.
99 * the base values were pseudorandom, all zero but one bit set, or
100 all zero plus a counter that starts at zero.
101
102 Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
103 satisfy this are
104 4 6 8 16 19 4
105 9 15 3 18 27 15
106 14 9 3 7 17 3
107 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
108 for "differ" defined as + with a one-bit base and a two-bit delta. I
109 used http://burtleburtle.net/bob/hash/avalanche.html to choose
110 the operations, constants, and arrangements of the variables.
111
112 This does not achieve avalanche. There are input bits of (a,b,c)
113 that fail to affect some output bits of (a,b,c), especially of a. The
114 most thoroughly mixed value is c, but it doesn't really even achieve
115 avalanche in c.
116
117 This allows some parallelism. Read-after-writes are good at doubling
118 the number of bits affected, so the goal of mixing pulls in the opposite
119 direction as the goal of parallelism. I did what I could. Rotates
120 seem to cost as much as shifts on every machine I could lay my hands
121 on, and rotates are much kinder to the top and bottom bits, so I used
122 rotates.
123 -------------------------------------------------------------------------------
124 */
125 #define mix(a,b,c) \
126 { \
127 a -= c; a ^= rot(c, 4); c += b; \
128 b -= a; b ^= rot(a, 6); a += c; \
129 c -= b; c ^= rot(b, 8); b += a; \
130 a -= c; a ^= rot(c,16); c += b; \
131 b -= a; b ^= rot(a,19); a += c; \
132 c -= b; c ^= rot(b, 4); b += a; \
133 }
134
135 /*
136 -------------------------------------------------------------------------------
137 final -- final mixing of 3 32-bit values (a,b,c) into c
138
139 Pairs of (a,b,c) values differing in only a few bits will usually
140 produce values of c that look totally different. This was tested for
141 * pairs that differed by one bit, by two bits, in any combination
142 of top bits of (a,b,c), or in any combination of bottom bits of
143 (a,b,c).
144 * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
145 the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
146 is commonly produced by subtraction) look like a single 1-bit
147 difference.
148 * the base values were pseudorandom, all zero but one bit set, or
149 all zero plus a counter that starts at zero.
150
151 These constants passed:
152 14 11 25 16 4 14 24
153 12 14 25 16 4 14 24
154 and these came close:
155 4 8 15 26 3 22 24
156 10 8 15 26 3 22 24
157 11 8 15 26 3 22 24
158 -------------------------------------------------------------------------------
159 */
160 #define final(a,b,c) \
161 { \
162 c ^= b; c -= rot(b,14); \
163 a ^= c; a -= rot(c,11); \
164 b ^= a; b -= rot(a,25); \
165 c ^= b; c -= rot(b,16); \
166 a ^= c; a -= rot(c,4); \
167 b ^= a; b -= rot(a,14); \
168 c ^= b; c -= rot(b,24); \
169 }
170
171 /*
172 --------------------------------------------------------------------
173 This works on all machines. To be useful, it requires
174 -- that the key be an array of uint32_t's, and
175 -- that the length be the number of uint32_t's in the key
176
177 The function hashword() is identical to hashlittle() on little-endian
178 machines, and identical to hashbig() on big-endian machines,
179 except that the length has to be measured in uint32_ts rather than in
180 bytes. hashlittle() is more complicated than hashword() only because
181 hashlittle() has to dance around fitting the key bytes into registers.
182 --------------------------------------------------------------------
183 */
184 #ifdef SELF_TEST
185 static
hashword(const uint32_t * k,size_t length,uint32_t initval)186 uint32_t hashword(
187 const uint32_t *k, /* the key, an array of uint32_t values */
188 size_t length, /* the length of the key, in uint32_ts */
189 uint32_t initval) /* the previous hash, or an arbitrary value */
190 {
191 uint32_t a,b,c;
192
193 /* Set up the internal state */
194 a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval;
195
196 /*------------------------------------------------- handle most of the key */
197 while (length > 3)
198 {
199 a += k[0];
200 b += k[1];
201 c += k[2];
202 mix(a,b,c);
203 length -= 3;
204 k += 3;
205 }
206
207 /*------------------------------------------- handle the last 3 uint32_t's */
208 switch(length) /* all the case statements fall through */
209 {
210 case 3 : c+=k[2];
211 case 2 : b+=k[1];
212 case 1 : a+=k[0];
213 final(a,b,c);
214 case 0: /* case 0: nothing left to add */
215 break;
216 }
217 /*------------------------------------------------------ report the result */
218 return c;
219 }
220
221 /*
222 --------------------------------------------------------------------
223 hashword2() -- same as hashword(), but take two seeds and return two
224 32-bit values. pc and pb must both be nonnull, and *pc and *pb must
225 both be initialized with seeds. If you pass in (*pb)==0, the output
226 (*pc) will be the same as the return value from hashword().
227 --------------------------------------------------------------------
228 */
229 static
hashword2(const uint32_t * k,size_t length,uint32_t * pc,uint32_t * pb)230 void hashword2 (
231 const uint32_t *k, /* the key, an array of uint32_t values */
232 size_t length, /* the length of the key, in uint32_ts */
233 uint32_t *pc, /* IN: seed OUT: primary hash value */
234 uint32_t *pb) /* IN: more seed OUT: secondary hash value */
235 {
236 uint32_t a,b,c;
237
238 /* Set up the internal state */
239 a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc;
240 c += *pb;
241
242 /*------------------------------------------------- handle most of the key */
243 while (length > 3)
244 {
245 a += k[0];
246 b += k[1];
247 c += k[2];
248 mix(a,b,c);
249 length -= 3;
250 k += 3;
251 }
252
253 /*------------------------------------------- handle the last 3 uint32_t's */
254 switch(length) /* all the case statements fall through */
255 {
256 case 3 : c+=k[2];
257 case 2 : b+=k[1];
258 case 1 : a+=k[0];
259 final(a,b,c);
260 case 0: /* case 0: nothing left to add */
261 break;
262 }
263 /*------------------------------------------------------ report the result */
264 *pc=c; *pb=b;
265 }
266
267 /*
268 * hashlittle2: return 2 32-bit hash values
269 *
270 * This is identical to hashlittle(), except it returns two 32-bit hash
271 * values instead of just one. This is good enough for hash table
272 * lookup with 2^^64 buckets, or if you want a second hash if you're not
273 * happy with the first, or if you want a probably-unique 64-bit ID for
274 * the key. *pc is better mixed than *pb, so use *pc first. If you want
275 * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
276 */
277 static void
hashlittle2(const void * key,size_t length,uint32_t * pc,uint32_t * pb)278 hashlittle2(
279 const void *key, /* the key to hash */
280 size_t length, /* length of the key */
281 uint32_t *pc, /* IN: primary initval, OUT: primary hash */
282 uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */
283 {
284 uint32_t a,b,c; /* internal state */
285 union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
286
287 /* Set up the internal state */
288 a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc;
289 c += *pb;
290
291 u.ptr = key;
292 if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
293 const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
294 const uint8_t *k8;
295
296 /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
297 while (length > 12)
298 {
299 a += k[0];
300 b += k[1];
301 c += k[2];
302 mix(a,b,c);
303 length -= 12;
304 k += 3;
305 }
306
307 /*----------------------------- handle the last (probably partial) block */
308 /*
309 * "k[2]&0xffffff" actually reads beyond the end of the string, but
310 * then masks off the part it's not allowed to read. Because the
311 * string is aligned, the masked-off tail is in the same word as the
312 * rest of the string. Every machine with memory protection I've seen
313 * does it on word boundaries, so is OK with this. But VALGRIND will
314 * still catch it and complain. The masking trick does make the hash
315 * noticeably faster for short strings (like English words).
316 */
317 #ifndef VALGRIND
318
319 switch(length)
320 {
321 case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
322 case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
323 case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
324 case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
325 case 8 : b+=k[1]; a+=k[0]; break;
326 case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
327 case 6 : b+=k[1]&0xffff; a+=k[0]; break;
328 case 5 : b+=k[1]&0xff; a+=k[0]; break;
329 case 4 : a+=k[0]; break;
330 case 3 : a+=k[0]&0xffffff; break;
331 case 2 : a+=k[0]&0xffff; break;
332 case 1 : a+=k[0]&0xff; break;
333 case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
334 }
335
336 #else /* make valgrind happy */
337
338 k8 = (const uint8_t *)k;
339 switch(length)
340 {
341 case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
342 case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
343 case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
344 case 9 : c+=k8[8]; /* fall through */
345 case 8 : b+=k[1]; a+=k[0]; break;
346 case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
347 case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
348 case 5 : b+=k8[4]; /* fall through */
349 case 4 : a+=k[0]; break;
350 case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
351 case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
352 case 1 : a+=k8[0]; break;
353 case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
354 }
355
356 #endif /* !valgrind */
357
358 } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
359 const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
360 const uint8_t *k8;
361
362 /*--------------- all but last block: aligned reads and different mixing */
363 while (length > 12)
364 {
365 a += k[0] + (((uint32_t)k[1])<<16);
366 b += k[2] + (((uint32_t)k[3])<<16);
367 c += k[4] + (((uint32_t)k[5])<<16);
368 mix(a,b,c);
369 length -= 12;
370 k += 6;
371 }
372
373 /*----------------------------- handle the last (probably partial) block */
374 k8 = (const uint8_t *)k;
375 switch(length)
376 {
377 case 12: c+=k[4]+(((uint32_t)k[5])<<16);
378 b+=k[2]+(((uint32_t)k[3])<<16);
379 a+=k[0]+(((uint32_t)k[1])<<16);
380 break;
381 case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
382 case 10: c+=k[4];
383 b+=k[2]+(((uint32_t)k[3])<<16);
384 a+=k[0]+(((uint32_t)k[1])<<16);
385 break;
386 case 9 : c+=k8[8]; /* fall through */
387 case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
388 a+=k[0]+(((uint32_t)k[1])<<16);
389 break;
390 case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
391 case 6 : b+=k[2];
392 a+=k[0]+(((uint32_t)k[1])<<16);
393 break;
394 case 5 : b+=k8[4]; /* fall through */
395 case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
396 break;
397 case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
398 case 2 : a+=k[0];
399 break;
400 case 1 : a+=k8[0];
401 break;
402 case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
403 }
404
405 } else { /* need to read the key one byte at a time */
406 const uint8_t *k = (const uint8_t *)key;
407
408 /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
409 while (length > 12)
410 {
411 a += k[0];
412 a += ((uint32_t)k[1])<<8;
413 a += ((uint32_t)k[2])<<16;
414 a += ((uint32_t)k[3])<<24;
415 b += k[4];
416 b += ((uint32_t)k[5])<<8;
417 b += ((uint32_t)k[6])<<16;
418 b += ((uint32_t)k[7])<<24;
419 c += k[8];
420 c += ((uint32_t)k[9])<<8;
421 c += ((uint32_t)k[10])<<16;
422 c += ((uint32_t)k[11])<<24;
423 mix(a,b,c);
424 length -= 12;
425 k += 12;
426 }
427
428 /*-------------------------------- last block: affect all 32 bits of (c) */
429 switch(length) /* all the case statements fall through */
430 {
431 case 12: c+=((uint32_t)k[11])<<24;
432 case 11: c+=((uint32_t)k[10])<<16;
433 case 10: c+=((uint32_t)k[9])<<8;
434 case 9 : c+=k[8];
435 case 8 : b+=((uint32_t)k[7])<<24;
436 case 7 : b+=((uint32_t)k[6])<<16;
437 case 6 : b+=((uint32_t)k[5])<<8;
438 case 5 : b+=k[4];
439 case 4 : a+=((uint32_t)k[3])<<24;
440 case 3 : a+=((uint32_t)k[2])<<16;
441 case 2 : a+=((uint32_t)k[1])<<8;
442 case 1 : a+=k[0];
443 break;
444 case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
445 }
446 }
447
448 final(a,b,c);
449 *pc=c; *pb=b;
450 }
451 #endif /*SELF_TEST*/
452
453
454 #ifdef WORDS_BIGENDIAN
455 /*
456 * hashbig():
457 * This is the same as hashword() on big-endian machines. It is different
458 * from hashlittle() on all machines. hashbig() takes advantage of
459 * big-endian byte ordering.
460 */
461 static uint32_t
hashbig(const void * key,size_t length,uint32_t initval)462 hashbig( const void *key, size_t length, uint32_t initval)
463 {
464 uint32_t a,b,c;
465 union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */
466
467 /* Set up the internal state */
468 a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
469
470 u.ptr = key;
471 if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) {
472 const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
473 const uint8_t *k8;
474
475 /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
476 while (length > 12)
477 {
478 a += k[0];
479 b += k[1];
480 c += k[2];
481 mix(a,b,c);
482 length -= 12;
483 k += 3;
484 }
485
486 /*----------------------------- handle the last (probably partial) block */
487 /*
488 * "k[2]<<8" actually reads beyond the end of the string, but
489 * then shifts out the part it's not allowed to read. Because the
490 * string is aligned, the illegal read is in the same word as the
491 * rest of the string. Every machine with memory protection I've seen
492 * does it on word boundaries, so is OK with this. But VALGRIND will
493 * still catch it and complain. The masking trick does make the hash
494 * noticeably faster for short strings (like English words).
495 */
496 #ifndef VALGRIND
497
498 switch(length)
499 {
500 case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
501 case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break;
502 case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break;
503 case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break;
504 case 8 : b+=k[1]; a+=k[0]; break;
505 case 7 : b+=k[1]&0xffffff00; a+=k[0]; break;
506 case 6 : b+=k[1]&0xffff0000; a+=k[0]; break;
507 case 5 : b+=k[1]&0xff000000; a+=k[0]; break;
508 case 4 : a+=k[0]; break;
509 case 3 : a+=k[0]&0xffffff00; break;
510 case 2 : a+=k[0]&0xffff0000; break;
511 case 1 : a+=k[0]&0xff000000; break;
512 case 0 : return c; /* zero length strings require no mixing */
513 }
514
515 #else /* make valgrind happy */
516
517 k8 = (const uint8_t *)k;
518 switch(length) /* all the case statements fall through */
519 {
520 case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
521 case 11: c+=((uint32_t)k8[10])<<8; /* fall through */
522 case 10: c+=((uint32_t)k8[9])<<16; /* fall through */
523 case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */
524 case 8 : b+=k[1]; a+=k[0]; break;
525 case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */
526 case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */
527 case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */
528 case 4 : a+=k[0]; break;
529 case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */
530 case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */
531 case 1 : a+=((uint32_t)k8[0])<<24; break;
532 case 0 : return c;
533 }
534
535 #endif /* !VALGRIND */
536
537 } else { /* need to read the key one byte at a time */
538 const uint8_t *k = (const uint8_t *)key;
539
540 /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
541 while (length > 12)
542 {
543 a += ((uint32_t)k[0])<<24;
544 a += ((uint32_t)k[1])<<16;
545 a += ((uint32_t)k[2])<<8;
546 a += ((uint32_t)k[3]);
547 b += ((uint32_t)k[4])<<24;
548 b += ((uint32_t)k[5])<<16;
549 b += ((uint32_t)k[6])<<8;
550 b += ((uint32_t)k[7]);
551 c += ((uint32_t)k[8])<<24;
552 c += ((uint32_t)k[9])<<16;
553 c += ((uint32_t)k[10])<<8;
554 c += ((uint32_t)k[11]);
555 mix(a,b,c);
556 length -= 12;
557 k += 12;
558 }
559
560 /*-------------------------------- last block: affect all 32 bits of (c) */
561 switch(length) /* all the case statements fall through */
562 {
563 case 12: c+=k[11];
564 case 11: c+=((uint32_t)k[10])<<8;
565 case 10: c+=((uint32_t)k[9])<<16;
566 case 9 : c+=((uint32_t)k[8])<<24;
567 case 8 : b+=k[7];
568 case 7 : b+=((uint32_t)k[6])<<8;
569 case 6 : b+=((uint32_t)k[5])<<16;
570 case 5 : b+=((uint32_t)k[4])<<24;
571 case 4 : a+=k[3];
572 case 3 : a+=((uint32_t)k[2])<<8;
573 case 2 : a+=((uint32_t)k[1])<<16;
574 case 1 : a+=((uint32_t)k[0])<<24;
575 break;
576 case 0 : return c;
577 }
578 }
579
580 final(a,b,c);
581 return c;
582 }
583 #endif /*WORDS_BIGENDIAN*/
584
585 /*
586 -------------------------------------------------------------------------------
587 hashlittle() -- hash a variable-length key into a 32-bit value
588 k : the key (the unaligned variable-length array of bytes)
589 length : the length of the key, counting by bytes
590 initval : can be any 4-byte value
591 Returns a 32-bit value. Every bit of the key affects every bit of
592 the return value. Two keys differing by one or two bits will have
593 totally different hash values.
594
595 The best hash table sizes are powers of 2. There is no need to do
596 mod a prime (mod is sooo slow!). If you need less than 32 bits,
597 use a bitmask. For example, if you need only 10 bits, do
598 h = (h & hashmask(10));
599 In which case, the hash table should have hashsize(10) elements.
600
601 If you are hashing n strings (uint8_t **)k, do it like this:
602 for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
603
604 By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
605 code any way you wish, private, educational, or commercial. It's free.
606
607 Use for hash table lookup, or anything where one collision in 2^^32 is
608 acceptable. Do NOT use for cryptographic purposes.
609 -------------------------------------------------------------------------------
610 */
611
612 static uint32_t
hashlittle(const void * key,size_t length,uint32_t initval)613 hashlittle( const void *key, size_t length, uint32_t initval)
614 {
615 uint32_t a,b,c; /* internal state */
616 union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
617
618 /* Set up the internal state */
619 a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
620
621 u.ptr = key;
622 if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
623 const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
624 const uint8_t *k8;
625
626 /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
627 while (length > 12)
628 {
629 a += k[0];
630 b += k[1];
631 c += k[2];
632 mix(a,b,c);
633 length -= 12;
634 k += 3;
635 }
636
637 /*----------------------------- handle the last (probably partial) block */
638 /*
639 * "k[2]&0xffffff" actually reads beyond the end of the string, but
640 * then masks off the part it's not allowed to read. Because the
641 * string is aligned, the masked-off tail is in the same word as the
642 * rest of the string. Every machine with memory protection I've seen
643 * does it on word boundaries, so is OK with this. But VALGRIND will
644 * still catch it and complain. The masking trick does make the hash
645 * noticeably faster for short strings (like English words).
646 */
647 #ifndef VALGRIND
648
649 switch(length)
650 {
651 case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
652 case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
653 case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
654 case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
655 case 8 : b+=k[1]; a+=k[0]; break;
656 case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
657 case 6 : b+=k[1]&0xffff; a+=k[0]; break;
658 case 5 : b+=k[1]&0xff; a+=k[0]; break;
659 case 4 : a+=k[0]; break;
660 case 3 : a+=k[0]&0xffffff; break;
661 case 2 : a+=k[0]&0xffff; break;
662 case 1 : a+=k[0]&0xff; break;
663 case 0 : return c; /* zero length strings require no mixing */
664 }
665
666 #else /* make valgrind happy */
667
668 k8 = (const uint8_t *)k;
669 switch(length)
670 {
671 case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
672 case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
673 case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
674 case 9 : c+=k8[8]; /* fall through */
675 case 8 : b+=k[1]; a+=k[0]; break;
676 case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
677 case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
678 case 5 : b+=k8[4]; /* fall through */
679 case 4 : a+=k[0]; break;
680 case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
681 case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
682 case 1 : a+=k8[0]; break;
683 case 0 : return c;
684 }
685
686 #endif /* !valgrind */
687
688 } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
689 const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
690 const uint8_t *k8;
691
692 /*--------------- all but last block: aligned reads and different mixing */
693 while (length > 12)
694 {
695 a += k[0] + (((uint32_t)k[1])<<16);
696 b += k[2] + (((uint32_t)k[3])<<16);
697 c += k[4] + (((uint32_t)k[5])<<16);
698 mix(a,b,c);
699 length -= 12;
700 k += 6;
701 }
702
703 /*----------------------------- handle the last (probably partial) block */
704 k8 = (const uint8_t *)k;
705 switch(length)
706 {
707 case 12: c+=k[4]+(((uint32_t)k[5])<<16);
708 b+=k[2]+(((uint32_t)k[3])<<16);
709 a+=k[0]+(((uint32_t)k[1])<<16);
710 break;
711 case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
712 case 10: c+=k[4];
713 b+=k[2]+(((uint32_t)k[3])<<16);
714 a+=k[0]+(((uint32_t)k[1])<<16);
715 break;
716 case 9 : c+=k8[8]; /* fall through */
717 case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
718 a+=k[0]+(((uint32_t)k[1])<<16);
719 break;
720 case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
721 case 6 : b+=k[2];
722 a+=k[0]+(((uint32_t)k[1])<<16);
723 break;
724 case 5 : b+=k8[4]; /* fall through */
725 case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
726 break;
727 case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
728 case 2 : a+=k[0];
729 break;
730 case 1 : a+=k8[0];
731 break;
732 case 0 : return c; /* zero length requires no mixing */
733 }
734
735 } else { /* need to read the key one byte at a time */
736 const uint8_t *k = (const uint8_t *)key;
737
738 /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
739 while (length > 12)
740 {
741 a += k[0];
742 a += ((uint32_t)k[1])<<8;
743 a += ((uint32_t)k[2])<<16;
744 a += ((uint32_t)k[3])<<24;
745 b += k[4];
746 b += ((uint32_t)k[5])<<8;
747 b += ((uint32_t)k[6])<<16;
748 b += ((uint32_t)k[7])<<24;
749 c += k[8];
750 c += ((uint32_t)k[9])<<8;
751 c += ((uint32_t)k[10])<<16;
752 c += ((uint32_t)k[11])<<24;
753 mix(a,b,c);
754 length -= 12;
755 k += 12;
756 }
757
758 /*-------------------------------- last block: affect all 32 bits of (c) */
759 switch(length) /* all the case statements fall through */
760 {
761 case 12: c+=((uint32_t)k[11])<<24;
762 case 11: c+=((uint32_t)k[10])<<16;
763 case 10: c+=((uint32_t)k[9])<<8;
764 case 9 : c+=k[8];
765 case 8 : b+=((uint32_t)k[7])<<24;
766 case 7 : b+=((uint32_t)k[6])<<16;
767 case 6 : b+=((uint32_t)k[5])<<8;
768 case 5 : b+=k[4];
769 case 4 : a+=((uint32_t)k[3])<<24;
770 case 3 : a+=((uint32_t)k[2])<<16;
771 case 2 : a+=((uint32_t)k[1])<<8;
772 case 1 : a+=k[0];
773 break;
774 case 0 : return c;
775 }
776 }
777
778 final(a,b,c);
779 return c;
780 }
781
782
783 /*
784 * hash_fast(key, length, initval)
785 * Wrapper that calls either hashlittle or hashbig, depending on endianness.
786 */
787 uint32_t
hash_fast(const void * key,size_t length)788 hash_fast( const void *key, size_t length) {
789 #define NC_ARBITRARY_UINT (992099683U)
790 #ifndef WORDS_BIGENDIAN
791 return hashlittle(key, length, NC_ARBITRARY_UINT);
792 #else
793 return hashbig(key, length, NC_ARBITRARY_UINT);
794 #endif
795 }
796
797 #ifdef SELF_TEST
798 /* used for timings */
driver1()799 void driver1()
800 {
801 uint8_t buf[256];
802 uint32_t i;
803 uint32_t h=0;
804 time_t a,z;
805
806 time(&a);
807 for (i=0; i<256; ++i) buf[i] = 'x';
808 for (i=0; i<1; ++i)
809 {
810 h = hashlittle(&buf[0],1,h);
811 }
812 time(&z);
813 if (z-a > 0) printf("time %d %.8x\n", z-a, h);
814 }
815
816 /* check that every input bit changes every output bit half the time */
817 #define HASHSTATE 1
818 #define HASHLEN 1
819 #define MAXPAIR 60
820 #define MAXLEN 70
driver2()821 void driver2()
822 {
823 uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
824 uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z;
825 uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
826 uint32_t x[HASHSTATE],y[HASHSTATE];
827 uint32_t hlen;
828
829 printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
830 for (hlen=0; hlen < MAXLEN; ++hlen)
831 {
832 z=0;
833 for (i=0; i<hlen; ++i) /*----------------------- for each input byte, */
834 {
835 for (j=0; j<8; ++j) /*------------------------ for each input bit, */
836 {
837 for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
838 {
839 for (l=0; l<HASHSTATE; ++l)
840 e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0);
841
842 /*---- check that every output bit is affected by that input bit */
843 for (k=0; k<MAXPAIR; k+=2)
844 {
845 uint32_t finished=1;
846 /* keys have one bit different */
847 for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;}
848 /* have a and b be two keys differing in only one bit */
849 a[i] ^= (k<<j);
850 a[i] ^= (k>>(8-j));
851 c[0] = hashlittle(a, hlen, m);
852 b[i] ^= ((k+1)<<j);
853 b[i] ^= ((k+1)>>(8-j));
854 d[0] = hashlittle(b, hlen, m);
855 /* check every bit is 1, 0, set, and not set at least once */
856 for (l=0; l<HASHSTATE; ++l)
857 {
858 e[l] &= (c[l]^d[l]);
859 f[l] &= ~(c[l]^d[l]);
860 g[l] &= c[l];
861 h[l] &= ~c[l];
862 x[l] &= d[l];
863 y[l] &= ~d[l];
864 if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
865 }
866 if (finished) break;
867 }
868 if (k>z) z=k;
869 if (k==MAXPAIR)
870 {
871 printf("Some bit didn't change: ");
872 printf("%.8x %.8x %.8x %.8x %.8x %.8x ",
873 e[0],f[0],g[0],h[0],x[0],y[0]);
874 printf("i %d j %d m %d len %d\n", i, j, m, hlen);
875 }
876 if (z==MAXPAIR) goto done;
877 }
878 }
879 }
880 done:
881 if (z < MAXPAIR)
882 {
883 printf("Mix success %2d bytes %2d initvals ",i,m);
884 printf("required %d trials\n", z/2);
885 }
886 }
887 printf("\n");
888 }
889
890 /* Check for reading beyond the end of the buffer and alignment problems */
driver3()891 void driver3()
892 {
893 uint8_t buf[MAXLEN+20], *b;
894 uint32_t len;
895 uint8_t q[] = "This is the time for all good men to come to the aid of their country...";
896 uint32_t h;
897 uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country...";
898 uint32_t i;
899 uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
900 uint32_t j;
901 uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
902 uint32_t ref,x,y;
903 uint8_t *p;
904
905 printf("Endianness. These lines should all be the same (for values filled in):\n");
906 printf("%.8x %.8x %.8x\n",
907 hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13),
908 hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13),
909 hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13));
910 p = q;
911 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
912 hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
913 hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
914 hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
915 hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
916 hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
917 hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
918 p = &qq[1];
919 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
920 hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
921 hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
922 hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
923 hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
924 hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
925 hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
926 p = &qqq[2];
927 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
928 hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
929 hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
930 hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
931 hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
932 hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
933 hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
934 p = &qqqq[3];
935 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
936 hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
937 hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
938 hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
939 hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
940 hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
941 hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
942 printf("\n");
943
944 /* check that hashlittle2 and hashlittle produce the same results */
945 i=47; j=0;
946 hashlittle2(q, sizeof(q), &i, &j);
947 if (hashlittle(q, sizeof(q), 47) != i)
948 printf("hashlittle2 and hashlittle mismatch\n");
949
950 /* check that hashword2 and hashword produce the same results */
951 len = 0xdeadbeef;
952 i=47, j=0;
953 hashword2(&len, 1, &i, &j);
954 if (hashword(&len, 1, 47) != i)
955 printf("hashword2 and hashword mismatch %x %x\n",
956 i, hashword(&len, 1, 47));
957
958 /* check hashlittle doesn't read before or after the ends of the string */
959 for (h=0, b=buf+1; h<8; ++h, ++b)
960 {
961 for (i=0; i<MAXLEN; ++i)
962 {
963 len = i;
964 for (j=0; j<i; ++j) *(b+j)=0;
965
966 /* these should all be equal */
967 ref = hashlittle(b, len, (uint32_t)1);
968 *(b+i)=(uint8_t)~0;
969 *(b-1)=(uint8_t)~0;
970 x = hashlittle(b, len, (uint32_t)1);
971 y = hashlittle(b, len, (uint32_t)1);
972 if ((ref != x) || (ref != y))
973 {
974 printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y,
975 h, i);
976 }
977 }
978 }
979 }
980
981 /* check for problems with nulls */
driver4()982 void driver4()
983 {
984 uint8_t buf[1];
985 uint32_t h,i,state[HASHSTATE];
986
987
988 buf[0] = ~0;
989 for (i=0; i<HASHSTATE; ++i) state[i] = 1;
990 printf("These should all be different\n");
991 for (i=0, h=0; i<8; ++i)
992 {
993 h = hashlittle(buf, 0, h);
994 printf("%2ld 0-byte strings, hash is %.8x\n", i, h);
995 }
996 }
997
driver5()998 void driver5()
999 {
1000 uint32_t b,c;
1001 b=0, c=0, hashlittle2("", 0, &c, &b);
1002 printf("hash is %.8lx %.8lx\n", c, b); /* deadbeef deadbeef */
1003 b=0xdeadbeef, c=0, hashlittle2("", 0, &c, &b);
1004 printf("hash is %.8lx %.8lx\n", c, b); /* bd5b7dde deadbeef */
1005 b=0xdeadbeef, c=0xdeadbeef, hashlittle2("", 0, &c, &b);
1006 printf("hash is %.8lx %.8lx\n", c, b); /* 9c093ccd bd5b7dde */
1007 b=0, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
1008 printf("hash is %.8lx %.8lx\n", c, b); /* 17770551 ce7226e6 */
1009 b=1, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
1010 printf("hash is %.8lx %.8lx\n", c, b); /* e3607cae bd371de4 */
1011 b=0, c=1, hashlittle2("Four score and seven years ago", 30, &c, &b);
1012 printf("hash is %.8lx %.8lx\n", c, b); /* cd628161 6cbea4b3 */
1013 c = hashlittle("Four score and seven years ago", 30, 0);
1014 printf("hash is %.8lx\n", c); /* 17770551 */
1015 c = hashlittle("Four score and seven years ago", 30, 1);
1016 printf("hash is %.8lx\n", c); /* cd628161 */
1017 }
1018
1019
main()1020 int main()
1021 {
1022 driver1(); /* test that the key is hashed: used for timings */
1023 driver2(); /* test that whole key is hashed thoroughly */
1024 driver3(); /* test that nothing but the key is hashed */
1025 driver4(); /* test hashing multiple buffers (all buffers are null) */
1026 driver5(); /* test the hash against known vectors */
1027 return 1;
1028 }
1029
1030 #endif /* SELF_TEST */
1031