Subversion Repositories mdb

Rev

Rev 22 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
21 andreas 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
 
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
uint32_t hashword(
174
	const uint32_t *k,                   /* the key, an array of uint32_t values */
175
	size_t          length,               /* the length of the key, in uint32_ts */
176
	uint32_t        initval)         /* the previous hash, or an arbitrary value */
177
{
178
	uint32_t a,b,c;
179
 
180
	/* Set up the internal state */
181
	a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval;
182
 
183
	/*------------------------------------------------- handle most of the key */
184
	while (length > 3)
185
	{
186
		a += k[0];
187
		b += k[1];
188
		c += k[2];
189
		mix(a,b,c);
190
		length -= 3;
191
		k += 3;
192
	}
193
 
194
	/*------------------------------------------- handle the last 3 uint32_t's */
195
	switch(length)                     /* all the case statements fall through */
196
	{ 
197
		case 3 : c+=k[2];
198
		case 2 : b+=k[1];
199
		case 1 : a+=k[0];
200
				 final(a,b,c);
201
		case 0:     /* case 0: nothing left to add */
202
		break;
203
	}
204
	/*------------------------------------------------------ report the result */
205
	return c;
206
}
207
 
208
/*
209
 * --------------------------------------------------------------------
210
 * hashword2() -- same as hashword(), but take two seeds and return two
211
 * 32-bit values.  pc and pb must both be nonnull, and *pc and *pb must
212
 * both be initialized with seeds.  If you pass in (*pb)==0, the output 
213
 * (*pc) will be the same as the return value from hashword().
214
 * --------------------------------------------------------------------
215
 */
216
void hashword2 (
217
	const uint32_t *k,                   /* the key, an array of uint32_t values */
218
	size_t          length,               /* the length of the key, in uint32_ts */
219
	uint32_t       *pc,                      /* IN: seed OUT: primary hash value */
220
	uint32_t       *pb)               /* IN: more seed OUT: secondary hash value */
221
{
222
	uint32_t a,b,c;
223
 
224
	/* Set up the internal state */
225
	a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc;
226
	c += *pb;
227
 
228
	/*------------------------------------------------- handle most of the key */
229
	while (length > 3)
230
	{
231
		a += k[0];
232
		b += k[1];
233
		c += k[2];
234
		mix(a,b,c);
235
		length -= 3;
236
		k += 3;
237
	}
238
 
239
	/*------------------------------------------- handle the last 3 uint32_t's */
240
	switch(length)                     /* all the case statements fall through */
241
	{ 
242
		case 3: c+=k[2];
243
		case 2: b+=k[1];
244
		case 1: a+=k[0];
245
				final(a,b,c);
246
		case 0:     /* case 0: nothing left to add */
247
			break;
248
	}
249
	/*------------------------------------------------------ report the result */
250
 
251
	*pc=c;
252
	*pb=b;
253
}
254
 
255
/*
256
 * -------------------------------------------------------------------------------
257
 * hashlittle() -- hash a variable-length key into a 32-bit value
258
 *  k       : the key (the unaligned variable-length array of bytes)
259
 *  length  : the length of the key, counting by bytes
260
 *  initval : can be any 4-byte value
261
 * Returns a 32-bit value.  Every bit of the key affects every bit of
262
 * the return value.  Two keys differing by one or two bits will have
263
 * totally different hash values.
264
 * 
265
 * The best hash table sizes are powers of 2.  There is no need to do
266
 * mod a prime (mod is sooo slow!).  If you need less than 32 bits,
267
 * use a bitmask.  For example, if you need only 10 bits, do
268
 *  h = (h & hashmask(10));
269
 * In which case, the hash table should have hashsize(10) elements.
270
 * 
271
 * If you are hashing n strings (uint8_t **)k, do it like this:
272
 *  for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
273
 * 
274
 * By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
275
 * code any way you wish, private, educational, or commercial.  It's free.
276
 * 
277
 * Use for hash table lookup, or anything where one collision in 2^^32 is
278
 * acceptable.  Do NOT use for cryptographic purposes.
279
 * -------------------------------------------------------------------------------
280
 */
281
 
282
uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
283
{
284
	uint32_t a,b,c;                                          /* internal state */
285
	union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */
286
 
287
     /* Set up the internal state */
288
	 a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
289
	 u.ptr = key;
290
 
291
	if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0))
292
	{
293
		const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
294
		const uint8_t  *k8;
295
 
296
		/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
297
		while (length > 12)
298
		{
299
			a += k[0];
300
			b += k[1];
301
			c += k[2];
302
			mix(a,b,c);
303
			length -= 12;
304
			k += 3;
305
		}
306
 
307
		/*----------------------------- handle the last (probably partial) block */
308
		/* 
309
		 * "k[2]&0xffffff" actually reads beyond the end of the string, but
310
		 * then masks off the part it's not allowed to read.  Because the
311
		 * string is aligned, the masked-off tail is in the same word as the
312
		 * rest of the string.  Every machine with memory protection I've seen
313
		 * does it on word boundaries, so is OK with this.  But VALGRIND will
314
		 * still catch it and complain.  The masking trick does make the hash
315
		 * noticably faster for short strings (like English words).
316
		 */
317
#ifndef VALGRIND
318
 
319
		switch(length)
320
		{
321
			case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
322
			case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
323
			case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
324
			case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
325
			case 8 : b+=k[1]; a+=k[0]; break;
326
			case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
327
			case 6 : b+=k[1]&0xffff; a+=k[0]; break;
328
			case 5 : b+=k[1]&0xff; a+=k[0]; break;
329
			case 4 : a+=k[0]; break;
330
			case 3 : a+=k[0]&0xffffff; break;
331
			case 2 : a+=k[0]&0xffff; break;
332
			case 1 : a+=k[0]&0xff; break;
333
			case 0 : return c;              /* zero length strings require no mixing */
334
		}
335
#else /* make valgrind happy */
336
		k8 = (const uint8_t *)k;
337
		switch(length)
338
		{
339
			case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
340
			case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
341
			case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
342
			case 9 : c+=k8[8];                   /* fall through */
343
			case 8 : b+=k[1]; a+=k[0]; break;
344
			case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
345
			case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
346
			case 5 : b+=k8[4];                   /* fall through */
347
			case 4 : a+=k[0]; break;
348
			case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
349
			case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
350
			case 1 : a+=k8[0]; break;
351
			case 0 : return c;
352
		}
353
#endif /* !valgrind */
354
	} else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0))
355
	{
356
		const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
357
		const uint8_t  *k8;
358
 
359
		/*--------------- all but last block: aligned reads and different mixing */
360
		while (length > 12)
361
		{
362
			a += k[0] + (((uint32_t)k[1])<<16);
363
			b += k[2] + (((uint32_t)k[3])<<16);
364
			c += k[4] + (((uint32_t)k[5])<<16);
365
			mix(a,b,c);
366
			length -= 12;
367
			k += 6;
368
		}
369
		/*----------------------------- handle the last (probably partial) block */
370
		k8 = (const uint8_t *)k;
371
 
372
		switch(length)
373
		{
374
			case 12:
375
				c+=k[4]+(((uint32_t)k[5])<<16);
376
				b+=k[2]+(((uint32_t)k[3])<<16);
377
				a+=k[0]+(((uint32_t)k[1])<<16);
378
			break;
379
 
380
			case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
381
 
382
			case 10:
383
				c+=k[4];
384
				b+=k[2]+(((uint32_t)k[3])<<16);
385
				a+=k[0]+(((uint32_t)k[1])<<16);
386
			break;
387
 
388
			case 9 : c+=k8[8];                      /* fall through */
389
 
390
			case 8 :
391
				b+=k[2]+(((uint32_t)k[3])<<16);
392
				a+=k[0]+(((uint32_t)k[1])<<16);
393
			break;
394
 
395
			case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
396
 
397
			case 6 :
398
				b+=k[2];
399
				a+=k[0]+(((uint32_t)k[1])<<16);
400
			break;
401
 
402
			case 5 : b+=k8[4];                      /* fall through */
403
			case 4 : a+=k[0]+(((uint32_t)k[1])<<16); break;
404
			case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
405
			case 2 : a+=k[0]; break;
406
			case 1 : a+=k8[0]; break;
407
			case 0 : return c;                     /* zero length requires no mixing */
408
		}
409
	}
410
	else                        /* need to read the key one byte at a time */
411
	{
412
		const uint8_t *k = (const uint8_t *)key;
413
 
414
		/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
415
		while (length > 12)
416
		{
417
			a += k[0];
418
			a += ((uint32_t)k[1])<<8;
419
			a += ((uint32_t)k[2])<<16;
420
			a += ((uint32_t)k[3])<<24;
421
			b += k[4];
422
			b += ((uint32_t)k[5])<<8;
423
			b += ((uint32_t)k[6])<<16;
424
			b += ((uint32_t)k[7])<<24;
425
			c += k[8];
426
			c += ((uint32_t)k[9])<<8;
427
			c += ((uint32_t)k[10])<<16;
428
			c += ((uint32_t)k[11])<<24;
429
			mix(a,b,c);
430
			length -= 12;
431
			k += 12;
432
		}
433
 
434
	    /*-------------------------------- last block: affect all 32 bits of (c) */
435
		switch(length)                   /* all the case statements fall through */
436
		{
437
			case 12: c+=((uint32_t)k[11])<<24;
438
			case 11: c+=((uint32_t)k[10])<<16;
439
			case 10: c+=((uint32_t)k[9])<<8;
440
			case 9 : c+=k[8];
441
			case 8 : b+=((uint32_t)k[7])<<24;
442
			case 7 : b+=((uint32_t)k[6])<<16;
443
			case 6 : b+=((uint32_t)k[5])<<8;
444
			case 5 : b+=k[4];
445
			case 4 : a+=((uint32_t)k[3])<<24;
446
			case 3 : a+=((uint32_t)k[2])<<16;
447
			case 2 : a+=((uint32_t)k[1])<<8;
448
			case 1 : a+=k[0];
449
			break;
450
			case 0 : return c;
451
		}
452
	}
453
 
454
	final(a,b,c);
455
	return c;
456
}
457
 
458
/*
459
 * hashlittle2: return 2 32-bit hash values
460
 *
461
 * This is identical to hashlittle(), except it returns two 32-bit hash
462
 * values instead of just one.  This is good enough for hash table
463
 * lookup with 2^^64 buckets, or if you want a second hash if you're not
464
 * happy with the first, or if you want a probably-unique 64-bit ID for
465
 * the key.  *pc is better mixed than *pb, so use *pc first.  If you want
466
 * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
467
 */
468
void hashlittle2(
469
		const void *key,       /* the key to hash */
470
		size_t      length,    /* length of the key */
471
		uint32_t   *pc,        /* IN: primary initval, OUT: primary hash */
472
		uint32_t   *pb)        /* IN: secondary initval, OUT: secondary hash */
473
{
474
	uint32_t a,b,c;                                          /* internal state */
475
	union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */
476
 
477
	/* Set up the internal state */
478
	a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc;
479
	c += *pb;
480
 
481
	u.ptr = key;
482
 
483
	if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0))
484
	{
485
		const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
486
		const uint8_t  *k8;
487
 
488
		/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
489
		while (length > 12)
490
		{
491
			a += k[0];
492
			b += k[1];
493
			c += k[2];
494
			mix(a,b,c);
495
			length -= 12;
496
			k += 3;
497
		}
498
 
499
		/*----------------------------- handle the last (probably partial) block */
500
		/* 
501
		 * "k[2]&0xffffff" actually reads beyond the end of the string, but
502
		 * then masks off the part it's not allowed to read.  Because the
503
		 * string is aligned, the masked-off tail is in the same word as the
504
		 * rest of the string.  Every machine with memory protection I've seen
505
		 * does it on word boundaries, so is OK with this.  But VALGRIND will
506
		 * still catch it and complain.  The masking trick does make the hash
507
		 * noticably faster for short strings (like English words).
508
		 */
509
#ifndef VALGRIND
510
		switch(length)
511
		{
512
			case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
513
			case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
514
			case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
515
			case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
516
			case 8 : b+=k[1]; a+=k[0]; break;
517
			case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
518
			case 6 : b+=k[1]&0xffff; a+=k[0]; break;
519
			case 5 : b+=k[1]&0xff; a+=k[0]; break;
520
			case 4 : a+=k[0]; break;
521
			case 3 : a+=k[0]&0xffffff; break;
522
			case 2 : a+=k[0]&0xffff; break;
523
			case 1 : a+=k[0]&0xff; break;
524
			case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
525
		}
526
#else /* make valgrind happy */
527
		k8 = (const uint8_t *)k;
528
		switch(length)
529
		{
530
			case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
531
			case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
532
			case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
533
			case 9 : c+=k8[8];                   /* fall through */
534
			case 8 : b+=k[1]; a+=k[0]; break;
535
			case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
536
			case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
537
			case 5 : b+=k8[4];                   /* fall through */
538
			case 4 : a+=k[0]; break;
539
			case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
540
			case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
541
			case 1 : a+=k8[0]; break;
542
			case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
543
		}
544
#endif /* !valgrind */
545
 
546
	}
547
	else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0))
548
	{
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:
568
				c+=k[4]+(((uint32_t)k[5])<<16);
569
				b+=k[2]+(((uint32_t)k[3])<<16);
570
				a+=k[0]+(((uint32_t)k[1])<<16);
571
			break;
572
 
573
			case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
574
 
575
			case 10:
576
				c+=k[4];
577
				b+=k[2]+(((uint32_t)k[3])<<16);
578
				a+=k[0]+(((uint32_t)k[1])<<16);
579
			break;
580
 
581
			case 9 : c+=k8[8];                      /* fall through */
582
 
583
			case 8 :
584
				b+=k[2]+(((uint32_t)k[3])<<16);
585
				a+=k[0]+(((uint32_t)k[1])<<16);
586
			break;
587
 
588
			case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
589
 
590
			case 6 :
591
				b+=k[2];
592
				a+=k[0]+(((uint32_t)k[1])<<16);
593
			break;
594
 
595
			case 5 : b+=k8[4];                      /* fall through */
596
			case 4 : a+=k[0]+(((uint32_t)k[1])<<16); break;
597
			case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
598
			case 2 : a+=k[0]; break;
599
			case 1 : a+=k8[0]; break;
600
			case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
601
		}
602
	}
603
	else                        /* need to read the key one byte at a time */
604
	{
605
		const uint8_t *k = (const uint8_t *)key;
606
 
607
		/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
608
		while (length > 12)
609
		{
610
			a += k[0];
611
			a += ((uint32_t)k[1])<<8;
612
			a += ((uint32_t)k[2])<<16;
613
			a += ((uint32_t)k[3])<<24;
614
			b += k[4];
615
			b += ((uint32_t)k[5])<<8;
616
			b += ((uint32_t)k[6])<<16;
617
			b += ((uint32_t)k[7])<<24;
618
			c += k[8];
619
			c += ((uint32_t)k[9])<<8;
620
			c += ((uint32_t)k[10])<<16;
621
			c += ((uint32_t)k[11])<<24;
622
			mix(a,b,c);
623
			length -= 12;
624
			k += 12;
625
		}
626
 
627
		/*-------------------------------- last block: affect all 32 bits of (c) */
628
		switch(length)                   /* all the case statements fall through */
629
		{
630
			case 12: c+=((uint32_t)k[11])<<24;
631
			case 11: c+=((uint32_t)k[10])<<16;
632
			case 10: c+=((uint32_t)k[9])<<8;
633
			case 9 : c+=k[8];
634
			case 8 : b+=((uint32_t)k[7])<<24;
635
			case 7 : b+=((uint32_t)k[6])<<16;
636
			case 6 : b+=((uint32_t)k[5])<<8;
637
			case 5 : b+=k[4];
638
			case 4 : a+=((uint32_t)k[3])<<24;
639
			case 3 : a+=((uint32_t)k[2])<<16;
640
			case 2 : a+=((uint32_t)k[1])<<8;
641
			case 1 : a+=k[0]; break;
642
			case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
643
		}
644
	}
645
 
646
	final(a,b,c);
647
	*pc=c; *pb=b;
648
}
649
 
650
/*
651
 * hashbig():
652
 * This is the same as hashword() on big-endian machines.  It is different
653
 * from hashlittle() on all machines.  hashbig() takes advantage of
654
 * big-endian byte ordering. 
655
 */
656
uint32_t hashbig( const void *key, size_t length, uint32_t initval)
657
{
658
	uint32_t a,b,c;
659
	union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */
660
 
661
	/* Set up the internal state */
662
	a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
663
	u.ptr = key;
664
 
665
	if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0))
666
	{
667
		const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
668
		const uint8_t  *k8;
669
 
670
		/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
671
		while (length > 12)
672
		{
673
			a += k[0];
674
			b += k[1];
675
			c += k[2];
676
			mix(a,b,c);
677
			length -= 12;
678
			k += 3;
679
		}
680
 
681
		/*----------------------------- handle the last (probably partial) block */
682
		/* 
683
		 * "k[2]<<8" actually reads beyond the end of the string, but
684
		 * then shifts out the part it's not allowed to read.  Because the
685
		 * string is aligned, the illegal read is in the same word as the
686
		 * rest of the string.  Every machine with memory protection I've seen
687
		 * does it on word boundaries, so is OK with this.  But VALGRIND will
688
		 * still catch it and complain.  The masking trick does make the hash
689
		 * noticably faster for short strings (like English words).
690
		 */
691
#ifndef VALGRIND
692
		switch(length)
693
		{
694
			case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
695
			case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break;
696
			case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break;
697
			case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break;
698
			case 8 : b+=k[1]; a+=k[0]; break;
699
			case 7 : b+=k[1]&0xffffff00; a+=k[0]; break;
700
			case 6 : b+=k[1]&0xffff0000; a+=k[0]; break;
701
			case 5 : b+=k[1]&0xff000000; a+=k[0]; break;
702
			case 4 : a+=k[0]; break;
703
			case 3 : a+=k[0]&0xffffff00; break;
704
			case 2 : a+=k[0]&0xffff0000; break;
705
			case 1 : a+=k[0]&0xff000000; break;
706
			case 0 : return c;              /* zero length strings require no mixing */
707
		}
708
#else  /* make valgrind happy */
709
		k8 = (const uint8_t *)k;
710
 
711
		switch(length)                   /* all the case statements fall through */
712
		{
713
			case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
714
			case 11: c+=((uint32_t)k8[10])<<8;  /* fall through */
715
			case 10: c+=((uint32_t)k8[9])<<16;  /* fall through */
716
			case 9 : c+=((uint32_t)k8[8])<<24;  /* fall through */
717
			case 8 : b+=k[1]; a+=k[0]; break;
718
			case 7 : b+=((uint32_t)k8[6])<<8;   /* fall through */
719
			case 6 : b+=((uint32_t)k8[5])<<16;  /* fall through */
720
			case 5 : b+=((uint32_t)k8[4])<<24;  /* fall through */
721
			case 4 : a+=k[0]; break;
722
			case 3 : a+=((uint32_t)k8[2])<<8;   /* fall through */
723
			case 2 : a+=((uint32_t)k8[1])<<16;  /* fall through */
724
			case 1 : a+=((uint32_t)k8[0])<<24; break;
725
			case 0 : return c;
726
	}
727
#endif /* !VALGRIND */
728
 
729
	}
730
	else                        /* need to read the key one byte at a time */
731
	{
732
		const uint8_t *k = (const uint8_t *)key;
733
 
734
		/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
735
		while (length > 12)
736
		{
737
			a += ((uint32_t)k[0])<<24;
738
			a += ((uint32_t)k[1])<<16;
739
			a += ((uint32_t)k[2])<<8;
740
			a += ((uint32_t)k[3]);
741
			b += ((uint32_t)k[4])<<24;
742
			b += ((uint32_t)k[5])<<16;
743
			b += ((uint32_t)k[6])<<8;
744
			b += ((uint32_t)k[7]);
745
			c += ((uint32_t)k[8])<<24;
746
			c += ((uint32_t)k[9])<<16;
747
			c += ((uint32_t)k[10])<<8;
748
			c += ((uint32_t)k[11]);
749
			mix(a,b,c);
750
			length -= 12;
751
			k += 12;
752
		}
753
 
754
		/*-------------------------------- last block: affect all 32 bits of (c) */
755
		switch(length)                   /* all the case statements fall through */
756
		{
757
			case 12: c+=k[11];
758
			case 11: c+=((uint32_t)k[10])<<8;
759
			case 10: c+=((uint32_t)k[9])<<16;
760
			case 9 : c+=((uint32_t)k[8])<<24;
761
			case 8 : b+=k[7];
762
			case 7 : b+=((uint32_t)k[6])<<8;
763
			case 6 : b+=((uint32_t)k[5])<<16;
764
			case 5 : b+=((uint32_t)k[4])<<24;
765
			case 4 : a+=k[3];
766
			case 3 : a+=((uint32_t)k[2])<<8;
767
			case 2 : a+=((uint32_t)k[1])<<16;
768
			case 1 : a+=((uint32_t)k[0])<<24; break;
769
			case 0 : return c;
770
		}
771
	}
772
 
773
	final(a,b,c);
774
	return c;
775
}
776
 
777
#ifdef SELF_TEST
778
/* used for timings */
779
void driver1()
780
{
781
	uint8_t buf[256];
782
	uint32_t i;
783
	uint32_t h=0;
784
	time_t a,z;
785
 
786
	time(&a);
787
 
788
	for (i=0; i<256; ++i)
789
		buf[i] = 'x';
790
 
791
	for (i=0; i<1; ++i) 
792
		h = hashlittle(&buf[0],1,h);
793
 
794
	time(&z);
795
 
796
	if (z-a > 0)
797
		printf("time %d %.8x\n", z-a, h);
798
}
799
 
800
/* check that every input bit changes every output bit half the time */
801
#define HASHSTATE 1
802
#define HASHLEN   1
803
#define MAXPAIR 60
804
#define MAXLEN  70
805
void driver2()
806
{
807
	uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
808
	uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z;
809
	uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
810
	uint32_t x[HASHSTATE],y[HASHSTATE];
811
	uint32_t hlen;
812
 
813
	printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
814
 
815
	for (hlen=0; hlen < MAXLEN; ++hlen)
816
	{
817
		z=0;
818
 
819
		for (i=0; i<hlen; ++i)  /*----------------------- for each input byte, */
820
		{
821
			for (j=0; j<8; ++j)   /*------------------------ for each input bit, */
822
			{
823
				for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
824
				{
825
					for (l=0; l<HASHSTATE; ++l)
826
						e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0);
827
 
828
					/*---- check that every output bit is affected by that input bit */
829
					for (k=0; k<MAXPAIR; k+=2)
830
					{ 
831
						uint32_t finished=1;
832
						/* keys have one bit different */
833
						for (l=0; l<hlen+1; ++l)
834
							a[l] = b[l] = (uint8_t)0;
835
 
836
						/* have a and b be two keys differing in only one bit */
837
						a[i] ^= (k<<j);
838
						a[i] ^= (k>>(8-j));
839
						c[0] = hashlittle(a, hlen, m);
840
						b[i] ^= ((k+1)<<j);
841
						b[i] ^= ((k+1)>>(8-j));
842
						d[0] = hashlittle(b, hlen, m);
843
						/* check every bit is 1, 0, set, and not set at least once */
844
						for (l=0; l<HASHSTATE; ++l)
845
						{
846
							e[l] &= (c[l]^d[l]);
847
							f[l] &= ~(c[l]^d[l]);
848
							g[l] &= c[l];
849
							h[l] &= ~c[l];
850
							x[l] &= d[l];
851
							y[l] &= ~d[l];
852
							if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
853
						}
854
 
855
						if (finished) break;
856
					}
857
 
858
					if (k>z)
859
						z=k;
860
 
861
					if (k==MAXPAIR) 
862
					{
863
						printf("Some bit didn't change: ");
864
						printf("%.8x %.8x %.8x %.8x %.8x %.8x  ", e[0],f[0],g[0],h[0],x[0],y[0]);
865
						printf("i %d j %d m %d len %d\n", i, j, m, hlen);
866
					}
867
 
868
					if (z==MAXPAIR)
869
						goto done;
870
				}
871
			}
872
		}
873
	done:
874
		if (z < MAXPAIR)
875
		{
876
			printf("Mix success  %2d bytes  %2d initvals  ",i,m);
877
			printf("required  %d  trials\n", z/2);
878
		}
879
	}
880
 
881
	printf("\n");
882
}
883
 
884
 /* Check for reading beyond the end of the buffer and alignment problems */
885
 void driver3()
886
 {
887
	 uint8_t buf[MAXLEN+20], *b;
888
	 uint32_t len;
889
	 uint8_t q[] = "This is the time for all good men to come to the aid of their country...";
890
	 uint32_t h;
891
	 uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country...";
892
	 uint32_t i;
893
	 uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
894
	 uint32_t j;
895
	 uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
896
	 uint32_t ref,x,y;
897
	 uint8_t *p;
898
 
899
	 printf("Endianness.  These lines should all be the same (for values filled in):\n");
900
	 printf("%.8x                            %.8x                            %.8x\n",
901
			hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13),
902
			hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13),
903
			hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13));
904
	 p = q;
905
	 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
906
			hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
907
			hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
908
			hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
909
			hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
910
			hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
911
			hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
912
	 p = &qq[1];
913
	 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
914
			hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
915
			hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
916
			hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
917
			hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
918
			hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
919
			hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
920
	 p = &qqq[2];
921
	 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
922
			hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
923
			hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
924
			hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
925
			hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
926
			hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
927
			hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
928
	 p = &qqqq[3];
929
	 printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
930
			hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
931
			hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
932
			hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
933
			hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
934
			hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
935
			hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
936
	 printf("\n");
937
 
938
	 /* check that hashlittle2 and hashlittle produce the same results */
939
	 i=47; j=0;
940
	 hashlittle2(q, sizeof(q), &i, &j);
941
	 if (hashlittle(q, sizeof(q), 47) != i)
942
		 printf("hashlittle2 and hashlittle mismatch\n");
943
 
944
	 /* check that hashword2 and hashword produce the same results */
945
	 len = 0xdeadbeef;
946
	 i=47, j=0;
947
	 hashword2(&len, 1, &i, &j);
948
	 if (hashword(&len, 1, 47) != i)
949
		 printf("hashword2 and hashword mismatch %x %x\n", 
950
				i, hashword(&len, 1, 47));
951
 
952
		 /* check hashlittle doesn't read before or after the ends of the string */
953
		 for (h=0, b=buf+1; h<8; ++h, ++b)
954
		 {
955
			 for (i=0; i<MAXLEN; ++i)
956
			 {
957
				 len = i;
958
				 for (j=0; j<i; ++j) *(b+j)=0;
959
 
960
				 /* these should all be equal */
961
				 ref = hashlittle(b, len, (uint32_t)1);
962
				 *(b+i)=(uint8_t)~0;
963
				 *(b-1)=(uint8_t)~0;
964
				 x = hashlittle(b, len, (uint32_t)1);
965
				 y = hashlittle(b, len, (uint32_t)1);
966
				 if ((ref != x) || (ref != y)) 
967
				 {
968
					 printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y,
969
							h, i);
970
				 }
971
			 }
972
		 }
973
 }
974
 
975
													 /* check for problems with nulls */
976
													 void driver4()
977
													 {
978
														 uint8_t buf[1];
979
														 uint32_t h,i,state[HASHSTATE];
980
 
981
 
982
														 buf[0] = ~0;
983
														 for (i=0; i<HASHSTATE; ++i) state[i] = 1;
984
														 printf("These should all be different\n");
985
														 for (i=0, h=0; i<8; ++i)
986
														 {
987
															 h = hashlittle(buf, 0, h);
988
															 printf("%2ld  0-byte strings, hash is  %.8x\n", i, h);
989
														 }
990
													 }
991
 
992
													 void driver5()
993
													 {
994
														 uint32_t b,c;
995
														 b=0, c=0, hashlittle2("", 0, &c, &b);
996
														 printf("hash is %.8lx %.8lx\n", c, b);   /* deadbeef deadbeef */
997
														 b=0xdeadbeef, c=0, hashlittle2("", 0, &c, &b);
998
														 printf("hash is %.8lx %.8lx\n", c, b);   /* bd5b7dde deadbeef */
999
														 b=0xdeadbeef, c=0xdeadbeef, hashlittle2("", 0, &c, &b);
1000
														 printf("hash is %.8lx %.8lx\n", c, b);   /* 9c093ccd bd5b7dde */
1001
														 b=0, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
1002
														 printf("hash is %.8lx %.8lx\n", c, b);   /* 17770551 ce7226e6 */
1003
														 b=1, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
1004
														 printf("hash is %.8lx %.8lx\n", c, b);   /* e3607cae bd371de4 */
1005
														 b=0, c=1, hashlittle2("Four score and seven years ago", 30, &c, &b);
1006
														 printf("hash is %.8lx %.8lx\n", c, b);   /* cd628161 6cbea4b3 */
1007
														 c = hashlittle("Four score and seven years ago", 30, 0);
1008
														 printf("hash is %.8lx\n", c);   /* 17770551 */
1009
														 c = hashlittle("Four score and seven years ago", 30, 1);
1010
														 printf("hash is %.8lx\n", c);   /* cd628161 */
1011
													 }
1012
 
1013
 
1014
													 int main()
1015
													 {
1016
														 driver1();   /* test that the key is hashed: used for timings */
1017
														 driver2();   /* test that whole key is hashed thoroughly */
1018
														 driver3();   /* test that nothing but the key is hashed */
1019
														 driver4();   /* test hashing multiple buffers (all buffers are null) */
1020
														 driver5();   /* test the hash against known vectors */
1021
														 return 1;
1022
													 }
1023
 
1024
													 #endif  /* SELF_TEST */
1025