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