blob: 0dad247ffe18664eab520baff5e8ab239490ad96 [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 **/
Harald Weltebed35df2011-11-02 13:06:18 +010020unsigned 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 */
jjakoc49cb302004-12-30 16:40:17 +000024{
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
Harald Weltebed35df2011-11-02 13:06:18 +010039 typedef unsigned long int ub4; /* unsigned 4-byte quantities */
Harald Weltebed35df2011-11-02 13:06:18 +010040 register unsigned long int a, b, c, len;
jjakoc49cb302004-12-30 16:40:17 +000041
Harald Weltebed35df2011-11-02 13:06:18 +010042 /* Set up the internal state */
43 len = length;
44 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
45 c = level; /* the previous hash value */
46
47 /*---------------------------------------- handle most of the key */
48 while (len >= 12) {
49 a += (k[0] + ((ub4) k[1] << 8) + ((ub4) k[2] << 16) +
50 ((ub4) k[3] << 24));
51 b += (k[4] + ((ub4) k[5] << 8) + ((ub4) k[6] << 16) +
52 ((ub4) k[7] << 24));
53 c += (k[8] + ((ub4) k[9] << 8) + ((ub4) k[10] << 16) +
54 ((ub4) k[11] << 24));
55 mix(a, b, c);
56 k += 12;
57 len -= 12;
58 }
59
60 /*------------------------------------- handle the last 11 bytes */
61 c += length;
62 switch (len) { /* all the case statements fall through */
63 case 11:
64 c += ((ub4) k[10] << 24);
65 case 10:
66 c += ((ub4) k[9] << 16);
67 case 9:
68 c += ((ub4) k[8] << 8);
69 /* the first byte of c is reserved for the length */
70 case 8:
71 b += ((ub4) k[7] << 24);
72 case 7:
73 b += ((ub4) k[6] << 16);
74 case 6:
75 b += ((ub4) k[5] << 8);
76 case 5:
77 b += k[4];
78 case 4:
79 a += ((ub4) k[3] << 24);
80 case 3:
81 a += ((ub4) k[2] << 16);
82 case 2:
83 a += ((ub4) k[1] << 8);
84 case 1:
85 a += k[0];
86 /* case 0: nothing left to add */
87 }
88 mix(a, b, c);
89 /*-------------------------------------------- report the result */
90 return c;
91}