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