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