blob: 02e2491100f6311911b9c90551f68b751e04da52 [file] [log] [blame]
jjakoc49cb302004-12-30 16:40:17 +00001/*
2 * Hash lookup function.
3 * Copyright (C) 2003, 2004 Mondru AB.
4 *
5 * The contents of this file may be used under the terms of the GNU
6 * General Public License Version 2, provided that the above copyright
7 * notice and this permission notice is included in all copies or
8 * substantial portions of the software.
9 *
10 */
11
12/**
13 * lookup()
14 * Generates a 32 bit hash.
15 * Based on public domain code by Bob Jenkins
16 * It should be one of the best hash functions around in terms of both
17 * statistical properties and speed. It is NOT recommended for cryptographic
18 * purposes.
19 **/
20unsigned long int lookup( k, length, level)
21register unsigned char *k; /* the key */
22register unsigned long int length; /* the length of the key */
23register unsigned long int level; /* the previous hash, or an arbitrary value*/
24{
25
26#define mix(a,b,c) \
27{ \
28 a -= b; a -= c; a ^= (c>>13); \
29 b -= c; b -= a; b ^= (a<<8); \
30 c -= a; c -= b; c ^= (b>>13); \
31 a -= b; a -= c; a ^= (c>>12); \
32 b -= c; b -= a; b ^= (a<<16); \
33 c -= a; c -= b; c ^= (b>>5); \
34 a -= b; a -= c; a ^= (c>>3); \
35 b -= c; b -= a; b ^= (a<<10); \
36 c -= a; c -= b; c ^= (b>>15); \
37}
38
39 typedef unsigned long int ub4; /* unsigned 4-byte quantities */
40 typedef unsigned char ub1; /* unsigned 1-byte quantities */
41 register unsigned long int a,b,c,len;
42
43 /* Set up the internal state */
44 len = length;
45 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
46 c = level; /* the previous hash value */
47
48 /*---------------------------------------- handle most of the key */
49 while (len >= 12)
50 {
51 a += (k[0] +((ub4)k[1]<<8) +((ub4)k[2]<<16) +((ub4)k[3]<<24));
52 b += (k[4] +((ub4)k[5]<<8) +((ub4)k[6]<<16) +((ub4)k[7]<<24));
53 c += (k[8] +((ub4)k[9]<<8) +((ub4)k[10]<<16)+((ub4)k[11]<<24));
54 mix(a,b,c);
55 k += 12; len -= 12;
56 }
57
58 /*------------------------------------- handle the last 11 bytes */
59 c += length;
60 switch(len) /* all the case statements fall through */
61 {
62 case 11: c+=((ub4)k[10]<<24);
63 case 10: c+=((ub4)k[9]<<16);
64 case 9 : c+=((ub4)k[8]<<8);
65 /* the first byte of c is reserved for the length */
66 case 8 : b+=((ub4)k[7]<<24);
67 case 7 : b+=((ub4)k[6]<<16);
68 case 6 : b+=((ub4)k[5]<<8);
69 case 5 : b+=k[4];
70 case 4 : a+=((ub4)k[3]<<24);
71 case 3 : a+=((ub4)k[2]<<16);
72 case 2 : a+=((ub4)k[1]<<8);
73 case 1 : a+=k[0];
74 /* case 0: nothing left to add */
75 }
76 mix(a,b,c);
77 /*-------------------------------------------- report the result */
78 return c;
79}
80