Integrated the DKIM signer into serv_smtpclient, but disabled it
[citadel.git] / libcitadel / lib / lookup3.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 hashword(), 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 hashword().  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 #include <stdio.h>      /* defines printf for tests */
39 #include <time.h>       /* defines time_t for timings in the test */
40 #include <stdint.h>     /* defines uint32_t etc */
41 #include <sys/param.h>  /* attempt to define endianness */
42 #ifdef linux
43 # include <endian.h>    /* attempt to define endianness */
44 #endif
45 #include "lookup3.h"
46 /*
47  * My best guess at if you are big-endian or little-endian.  This may
48  * need adjustment.
49  */
50 #if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
51      __BYTE_ORDER == __LITTLE_ENDIAN) || \
52     (defined(i386) || defined(__i386__) || defined(__i486__) || \
53      defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
54 # define HASH_LITTLE_ENDIAN 1
55 # define HASH_BIG_ENDIAN 0
56 #elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
57        __BYTE_ORDER == __BIG_ENDIAN) || \
58       (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
59 # define HASH_LITTLE_ENDIAN 0
60 # define HASH_BIG_ENDIAN 1
61 #else
62 # define HASH_LITTLE_ENDIAN 0
63 # define HASH_BIG_ENDIAN 0
64 #endif
65
66 #define hashsize(n) ((uint32_t)1<<(n))
67 #define hashmask(n) (hashsize(n)-1)
68 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
69
70 /*
71 -------------------------------------------------------------------------------
72 mix -- mix 3 32-bit values reversibly.
73
74 This is reversible, so any information in (a,b,c) before mix() is
75 still in (a,b,c) after mix().
76
77 If four pairs of (a,b,c) inputs are run through mix(), or through
78 mix() in reverse, there are at least 32 bits of the output that
79 are sometimes the same for one pair and different for another pair.
80 This was tested for:
81 * pairs that differed by one bit, by two bits, in any combination
82   of top bits of (a,b,c), or in any combination of bottom bits of
83   (a,b,c).
84 * "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
85   the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
86   is commonly produced by subtraction) look like a single 1-bit
87   difference.
88 * the base values were pseudorandom, all zero but one bit set, or 
89   all zero plus a counter that starts at zero.
90
91 Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
92 satisfy this are
93     4  6  8 16 19  4
94     9 15  3 18 27 15
95    14  9  3  7 17  3
96 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
97 for "differ" defined as + with a one-bit base and a two-bit delta.  I
98 used http://burtleburtle.net/bob/hash/avalanche.html to choose 
99 the operations, constants, and arrangements of the variables.
100
101 This does not achieve avalanche.  There are input bits of (a,b,c)
102 that fail to affect some output bits of (a,b,c), especially of a.  The
103 most thoroughly mixed value is c, but it doesn't really even achieve
104 avalanche in c.
105
106 This allows some parallelism.  Read-after-writes are good at doubling
107 the number of bits affected, so the goal of mixing pulls in the opposite
108 direction as the goal of parallelism.  I did what I could.  Rotates
109 seem to cost as much as shifts on every machine I could lay my hands
110 on, and rotates are much kinder to the top and bottom bits, so I used
111 rotates.
112 -------------------------------------------------------------------------------
113 */
114 #define mix(a,b,c) \
115 { \
116   a -= c;  a ^= rot(c, 4);  c += b; \
117   b -= a;  b ^= rot(a, 6);  a += c; \
118   c -= b;  c ^= rot(b, 8);  b += a; \
119   a -= c;  a ^= rot(c,16);  c += b; \
120   b -= a;  b ^= rot(a,19);  a += c; \
121   c -= b;  c ^= rot(b, 4);  b += a; \
122 }
123
124 /*
125 -------------------------------------------------------------------------------
126 final -- final mixing of 3 32-bit values (a,b,c) into c
127
128 Pairs of (a,b,c) values differing in only a few bits will usually
129 produce values of c that look totally different.  This was tested for
130 * pairs that differed by one bit, by two bits, in any combination
131   of top bits of (a,b,c), or in any combination of bottom bits of
132   (a,b,c).
133 * "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
134   the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
135   is commonly produced by subtraction) look like a single 1-bit
136   difference.
137 * the base values were pseudorandom, all zero but one bit set, or 
138   all zero plus a counter that starts at zero.
139
140 These constants passed:
141  14 11 25 16 4 14 24
142  12 14 25 16 4 14 24
143 and these came close:
144   4  8 15 26 3 22 24
145  10  8 15 26 3 22 24
146  11  8 15 26 3 22 24
147 -------------------------------------------------------------------------------
148 */
149 #define final(a,b,c) \
150 { \
151   c ^= b; c -= rot(b,14); \
152   a ^= c; a -= rot(c,11); \
153   b ^= a; b -= rot(a,25); \
154   c ^= b; c -= rot(b,16); \
155   a ^= c; a -= rot(c,4);  \
156   b ^= a; b -= rot(a,14); \
157   c ^= b; c -= rot(b,24); \
158 }
159
160 /*
161 --------------------------------------------------------------------
162  This works on all machines.  To be useful, it requires
163  -- that the key be an array of uint32_t's, and
164  -- that the length be the number of uint32_t's in the key
165
166  The function hashword() is identical to hashlittle() on little-endian
167  machines, and identical to hashbig() on big-endian machines,
168  except that the length has to be measured in uint32_ts rather than in
169  bytes.  hashlittle() is more complicated than hashword() only because
170  hashlittle() has to dance around fitting the key bytes into registers.
171 --------------------------------------------------------------------
172 */
173 #if 0 // libcitadel doesn't use this.
174 uint32_t hashword(
175 const uint32_t *k,                   /* the key, an array of uint32_t values */
176 size_t          length,               /* the length of the key, in uint32_ts */
177 uint32_t        initval)         /* the previous hash, or an arbitrary value */
178 {
179   uint32_t a,b,c;
180
181   /* Set up the internal state */
182   a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval;
183
184   /*------------------------------------------------- handle most of the key */
185   while (length > 3)
186   {
187     a += k[0];
188     b += k[1];
189     c += k[2];
190     mix(a,b,c);
191     length -= 3;
192     k += 3;
193   }
194
195   /*------------------------------------------- handle the last 3 uint32_t's */
196   switch(length)                     /* all the case statements fall through */
197   { 
198   case 3 : c+=k[2];
199   case 2 : b+=k[1];
200   case 1 : a+=k[0];
201     final(a,b,c);
202   case 0:     /* case 0: nothing left to add */
203     break;
204   }
205   /*------------------------------------------------------ report the result */
206   return c;
207 }
208 #endif 
209
210 /*
211 --------------------------------------------------------------------
212 hashword2() -- same as hashword(), but take two seeds and return two
213 32-bit values.  pc and pb must both be nonnull, and *pc and *pb must
214 both be initialized with seeds.  If you pass in (*pb)==0, the output 
215 (*pc) will be the same as the return value from hashword().
216 --------------------------------------------------------------------
217 */
218 #if 0 // libcitadel doesn't use this.
219 void hashword2 (
220 const uint32_t *k,                   /* the key, an array of uint32_t values */
221 size_t          length,               /* the length of the key, in uint32_ts */
222 uint32_t       *pc,                      /* IN: seed OUT: primary hash value */
223 uint32_t       *pb)               /* IN: more seed OUT: secondary hash value */
224 {
225   uint32_t a,b,c;
226
227   /* Set up the internal state */
228   a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc;
229   c += *pb;
230
231   /*------------------------------------------------- handle most of the key */
232   while (length > 3)
233   {
234     a += k[0];
235     b += k[1];
236     c += k[2];
237     mix(a,b,c);
238     length -= 3;
239     k += 3;
240   }
241
242   /*------------------------------------------- handle the last 3 uint32_t's */
243   switch(length)                     /* all the case statements fall through */
244   { 
245   case 3 : c+=k[2];
246   case 2 : b+=k[1];
247   case 1 : a+=k[0];
248     final(a,b,c);
249   case 0:     /* case 0: nothing left to add */
250     break;
251   }
252   /*------------------------------------------------------ report the result */
253   *pc=c; *pb=b;
254 }
255 #endif
256
257 /*
258 -------------------------------------------------------------------------------
259 hashlittle() -- hash a variable-length key into a 32-bit value
260   k       : the key (the unaligned variable-length array of bytes)
261   length  : the length of the key, counting by bytes
262   initval : can be any 4-byte value
263 Returns a 32-bit value.  Every bit of the key affects every bit of
264 the return value.  Two keys differing by one or two bits will have
265 totally different hash values.
266
267 The best hash table sizes are powers of 2.  There is no need to do
268 mod a prime (mod is sooo slow!).  If you need less than 32 bits,
269 use a bitmask.  For example, if you need only 10 bits, do
270   h = (h & hashmask(10));
271 In which case, the hash table should have hashsize(10) elements.
272
273 If you are hashing n strings (uint8_t **)k, do it like this:
274   for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
275
276 By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
277 code any way you wish, private, educational, or commercial.  It's free.
278
279 Use for hash table lookup, or anything where one collision in 2^^32 is
280 acceptable.  Do NOT use for cryptographic purposes.
281 -------------------------------------------------------------------------------
282 */
283
284 uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
285 {
286   uint32_t a,b,c;                                          /* internal state */
287   union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */
288
289   /* Set up the internal state */
290   a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
291
292   u.ptr = key;
293   if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
294     const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
295 #ifdef VALGRIND
296     const uint8_t  *k8;
297 #endif
298     /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
299     while (length > 12)
300     {
301       a += k[0];
302       b += k[1];
303       c += k[2];
304       mix(a,b,c);
305       length -= 12;
306       k += 3;
307     }
308
309     /*----------------------------- handle the last (probably partial) block */
310     /* 
311      * "k[2]&0xffffff" actually reads beyond the end of the string, but
312      * then masks off the part it's not allowed to read.  Because the
313      * string is aligned, the masked-off tail is in the same word as the
314      * rest of the string.  Every machine with memory protection I've seen
315      * does it on word boundaries, so is OK with this.  But VALGRIND will
316      * still catch it and complain.  The masking trick does make the hash
317      * noticably faster for short strings (like English words).
318      */
319 #ifndef VALGRIND
320
321     switch(length)
322     {
323     case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
324     case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
325     case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
326     case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
327     case 8 : b+=k[1]; a+=k[0]; break;
328     case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
329     case 6 : b+=k[1]&0xffff; a+=k[0]; break;
330     case 5 : b+=k[1]&0xff; a+=k[0]; break;
331     case 4 : a+=k[0]; break;
332     case 3 : a+=k[0]&0xffffff; break;
333     case 2 : a+=k[0]&0xffff; break;
334     case 1 : a+=k[0]&0xff; break;
335     case 0 : return c;              /* zero length strings require no mixing */
336     }
337
338 #else /* make valgrind happy */
339
340     k8 = (const uint8_t *)k;
341     switch(length)
342     {
343     case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
344     case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
345     case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
346     case 9 : c+=k8[8];                   /* fall through */
347     case 8 : b+=k[1]; a+=k[0]; break;
348     case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
349     case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
350     case 5 : b+=k8[4];                   /* fall through */
351     case 4 : a+=k[0]; break;
352     case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
353     case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
354     case 1 : a+=k8[0]; break;
355     case 0 : return c;
356     }
357
358 #endif /* !valgrind */
359
360   } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
361     const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
362     const uint8_t  *k8;
363
364     /*--------------- all but last block: aligned reads and different mixing */
365     while (length > 12)
366     {
367       a += k[0] + (((uint32_t)k[1])<<16);
368       b += k[2] + (((uint32_t)k[3])<<16);
369       c += k[4] + (((uint32_t)k[5])<<16);
370       mix(a,b,c);
371       length -= 12;
372       k += 6;
373     }
374
375     /*----------------------------- handle the last (probably partial) block */
376     k8 = (const uint8_t *)k;
377     switch(length)
378     {
379     case 12: c+=k[4]+(((uint32_t)k[5])<<16);
380              b+=k[2]+(((uint32_t)k[3])<<16);
381              a+=k[0]+(((uint32_t)k[1])<<16);
382              break;
383     case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
384     case 10: c+=k[4];
385              b+=k[2]+(((uint32_t)k[3])<<16);
386              a+=k[0]+(((uint32_t)k[1])<<16);
387              break;
388     case 9 : c+=k8[8];                      /* fall through */
389     case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
390              a+=k[0]+(((uint32_t)k[1])<<16);
391              break;
392     case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
393     case 6 : b+=k[2];
394              a+=k[0]+(((uint32_t)k[1])<<16);
395              break;
396     case 5 : b+=k8[4];                      /* fall through */
397     case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
398              break;
399     case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
400     case 2 : a+=k[0];
401              break;
402     case 1 : a+=k8[0];
403              break;
404     case 0 : return c;                     /* zero length requires no mixing */
405     }
406
407   } else {                        /* need to read the key one byte at a time */
408     const uint8_t *k = (const uint8_t *)key;
409
410     /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
411     while (length > 12)
412     {
413       a += k[0];
414       a += ((uint32_t)k[1])<<8;
415       a += ((uint32_t)k[2])<<16;
416       a += ((uint32_t)k[3])<<24;
417       b += k[4];
418       b += ((uint32_t)k[5])<<8;
419       b += ((uint32_t)k[6])<<16;
420       b += ((uint32_t)k[7])<<24;
421       c += k[8];
422       c += ((uint32_t)k[9])<<8;
423       c += ((uint32_t)k[10])<<16;
424       c += ((uint32_t)k[11])<<24;
425       mix(a,b,c);
426       length -= 12;
427       k += 12;
428     }
429
430     /*-------------------------------- last block: affect all 32 bits of (c) */
431     switch(length)                   /* all the case statements fall through */
432     {
433     case 12: c+=((uint32_t)k[11])<<24;
434     case 11: c+=((uint32_t)k[10])<<16;
435     case 10: c+=((uint32_t)k[9])<<8;
436     case 9 : c+=k[8];
437     case 8 : b+=((uint32_t)k[7])<<24;
438     case 7 : b+=((uint32_t)k[6])<<16;
439     case 6 : b+=((uint32_t)k[5])<<8;
440     case 5 : b+=k[4];
441     case 4 : a+=((uint32_t)k[3])<<24;
442     case 3 : a+=((uint32_t)k[2])<<16;
443     case 2 : a+=((uint32_t)k[1])<<8;
444     case 1 : a+=k[0];
445              break;
446     case 0 : return c;
447     }
448   }
449
450   final(a,b,c);
451   return c;
452 }
453
454
455 /*
456  * hashlittle2: return 2 32-bit hash values
457  *
458  * This is identical to hashlittle(), except it returns two 32-bit hash
459  * values instead of just one.  This is good enough for hash table
460  * lookup with 2^^64 buckets, or if you want a second hash if you're not
461  * happy with the first, or if you want a probably-unique 64-bit ID for
462  * the key.  *pc is better mixed than *pb, so use *pc first.  If you want
463  * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
464  */
465 #if 0 // libcitadel doesn't use this.
466 void 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 #ifdef VALGRIND
483     const uint8_t  *k8;
484 #endif
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 hashword() on big-endian machines.  It is different
647  * from hashlittle() on all machines.  hashbig() takes advantage of
648  * big-endian byte ordering. 
649  */
650 #if 0 // libcitadel doesn't use this.
651 uint32_t hashbig( const void *key, size_t length, uint32_t initval)
652 {
653   uint32_t a,b,c;
654   union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */
655
656   /* Set up the internal state */
657   a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
658
659   u.ptr = key;
660   if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) {
661     const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
662 #ifdef VALGRIND
663     const uint8_t  *k8;
664 #endif
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 #endif
774
775 #ifdef SELF_TEST
776
777 /* used for timings */
778 void driver1()
779 {
780   uint8_t buf[256];
781   uint32_t i;
782   uint32_t h=0;
783   time_t a,z;
784
785   time(&a);
786   for (i=0; i<256; ++i) buf[i] = 'x';
787   for (i=0; i<1; ++i) 
788   {
789     h = hashlittle(&buf[0],1,h);
790   }
791   time(&z);
792   if (z-a > 0) printf("time %d %.8x\n", z-a, h);
793 }
794
795 /* check that every input bit changes every output bit half the time */
796 #define HASHSTATE 1
797 #define HASHLEN   1
798 #define MAXPAIR 60
799 #define MAXLEN  70
800 void driver2()
801 {
802   uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
803   uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z;
804   uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
805   uint32_t x[HASHSTATE],y[HASHSTATE];
806   uint32_t hlen;
807
808   printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
809   for (hlen=0; hlen < MAXLEN; ++hlen)
810   {
811     z=0;
812     for (i=0; i<hlen; ++i)  /*----------------------- for each input byte, */
813     {
814       for (j=0; j<8; ++j)   /*------------------------ for each input bit, */
815       {
816         for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
817         {
818           for (l=0; l<HASHSTATE; ++l)
819             e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0);
820
821           /*---- check that every output bit is affected by that input bit */
822           for (k=0; k<MAXPAIR; k+=2)
823           { 
824             uint32_t finished=1;
825             /* keys have one bit different */
826             for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;}
827             /* have a and b be two keys differing in only one bit */
828             a[i] ^= (k<<j);
829             a[i] ^= (k>>(8-j));
830              c[0] = hashlittle(a, hlen, m);
831             b[i] ^= ((k+1)<<j);
832             b[i] ^= ((k+1)>>(8-j));
833              d[0] = hashlittle(b, hlen, m);
834             /* check every bit is 1, 0, set, and not set at least once */
835             for (l=0; l<HASHSTATE; ++l)
836             {
837               e[l] &= (c[l]^d[l]);
838               f[l] &= ~(c[l]^d[l]);
839               g[l] &= c[l];
840               h[l] &= ~c[l];
841               x[l] &= d[l];
842               y[l] &= ~d[l];
843               if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
844             }
845             if (finished) break;
846           }
847           if (k>z) z=k;
848           if (k==MAXPAIR) 
849           {
850              printf("Some bit didn't change: ");
851              printf("%.8x %.8x %.8x %.8x %.8x %.8x  ",
852                     e[0],f[0],g[0],h[0],x[0],y[0]);
853              printf("i %d j %d m %d len %d\n", i, j, m, hlen);
854           }
855           if (z==MAXPAIR) goto done;
856         }
857       }
858     }
859    done:
860     if (z < MAXPAIR)
861     {
862       printf("Mix success  %2d bytes  %2d initvals  ",i,m);
863       printf("required  %d  trials\n", z/2);
864     }
865   }
866   printf("\n");
867 }
868
869 /* Check for reading beyond the end of the buffer and alignment problems */
870 void driver3()
871 {
872   uint8_t buf[MAXLEN+20], *b;
873   uint32_t len;
874   uint8_t q[] = "This is the time for all good men to come to the aid of their country...";
875   uint32_t h;
876   uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country...";
877   uint32_t i;
878   uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
879   uint32_t j;
880   uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
881   uint32_t ref,x,y;
882   uint8_t *p;
883
884   printf("Endianness.  These lines should all be the same (for values filled in):\n");
885   printf("%.8x                            %.8x                            %.8x\n",
886          hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13),
887          hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13),
888          hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13));
889   p = q;
890   printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
891          hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
892          hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
893          hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
894          hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
895          hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
896          hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
897   p = &qq[1];
898   printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
899          hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
900          hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
901          hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
902          hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
903          hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
904          hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
905   p = &qqq[2];
906   printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
907          hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
908          hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
909          hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
910          hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
911          hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
912          hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
913   p = &qqqq[3];
914   printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
915          hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
916          hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
917          hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
918          hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
919          hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
920          hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
921   printf("\n");
922
923   /* check that hashlittle2 and hashlittle produce the same results */
924   i=47; j=0;
925   hashlittle2(q, sizeof(q), &i, &j);
926   if (hashlittle(q, sizeof(q), 47) != i)
927     printf("hashlittle2 and hashlittle mismatch\n");
928
929   /* check that hashword2 and hashword produce the same results */
930   len = 0xdeadbeef;
931   i=47, j=0;
932   hashword2(&len, 1, &i, &j);
933   if (hashword(&len, 1, 47) != i)
934     printf("hashword2 and hashword mismatch %x %x\n", 
935            i, hashword(&len, 1, 47));
936
937   /* check hashlittle doesn't read before or after the ends of the string */
938   for (h=0, b=buf+1; h<8; ++h, ++b)
939   {
940     for (i=0; i<MAXLEN; ++i)
941     {
942       len = i;
943       for (j=0; j<i; ++j) *(b+j)=0;
944
945       /* these should all be equal */
946       ref = hashlittle(b, len, (uint32_t)1);
947       *(b+i)=(uint8_t)~0;
948       *(b-1)=(uint8_t)~0;
949       x = hashlittle(b, len, (uint32_t)1);
950       y = hashlittle(b, len, (uint32_t)1);
951       if ((ref != x) || (ref != y)) 
952       {
953         printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y,
954                h, i);
955       }
956     }
957   }
958 }
959
960 /* check for problems with nulls */
961  void driver4()
962 {
963   uint8_t buf[1];
964   uint32_t h,i,state[HASHSTATE];
965
966
967   buf[0] = ~0;
968   for (i=0; i<HASHSTATE; ++i) state[i] = 1;
969   printf("These should all be different\n");
970   for (i=0, h=0; i<8; ++i)
971   {
972     h = hashlittle(buf, 0, h);
973     printf("%2ld  0-byte strings, hash is  %.8x\n", i, h);
974   }
975 }
976
977
978 int main()
979 {
980   driver1();   /* test that the key is hashed: used for timings */
981   driver2();   /* test that whole key is hashed thoroughly */
982   driver3();   /* test that nothing but the key is hashed */
983   driver4();   /* test hashing multiple buffers (all buffers are null) */
984   return 1;
985 }
986
987 #endif  /* SELF_TEST */