提交 8f694f39 authored 作者: Thomas Mueller's avatar Thomas Mueller

Better (non-universal) fast hash function

上级 7dcfa24a
...@@ -136,7 +136,7 @@ public class TestPerfectHash extends TestBase { ...@@ -136,7 +136,7 @@ public class TestPerfectHash extends TestBase {
if (index < badUntilLevel) { if (index < badUntilLevel) {
return 0; return 0;
} }
return StringHash.getFastHash(o, index); return StringHash.getFastHash(o, index, seed);
} }
}; };
...@@ -233,14 +233,17 @@ public class TestPerfectHash extends TestBase { ...@@ -233,14 +233,17 @@ public class TestPerfectHash extends TestBase {
} }
public int hashCode(int index, int seed) { public int hashCode(int index, int seed) {
if (index < 4) { if (index < 8) {
int result = 0; int x = (index * 0x9f3b) ^ seed;
int x = seed + index; int result = seed;
int end = start; int p = start;
while (data[end] != '\n') { while (true) {
int c = data[p++] & 255;
if (c == '\n') {
break;
}
x = 31 + x * 0x9f3b; x = 31 + x * 0x9f3b;
result += x * (1 + (data[end] & 255)); result ^= x * (1 + c);
end++;
} }
return result; return result;
} }
......
...@@ -645,8 +645,8 @@ public class MinimalPerfectHash<K> { ...@@ -645,8 +645,8 @@ public class MinimalPerfectHash<K> {
return o.hashCode(); return o.hashCode();
} else if (index < 8) { } else if (index < 8) {
// use a different hash function, which is fast but not // use a different hash function, which is fast but not
// cryptographically secure // necessarily universal, and not cryptographically secure
return getFastHash(o, index ^ seed); return getFastHash(o, index, seed);
} }
// this method is supposed to be cryptographically secure; // this method is supposed to be cryptographically secure;
// we could use SHA-256 for higher indexes // we could use SHA-256 for higher indexes
...@@ -657,14 +657,16 @@ public class MinimalPerfectHash<K> { ...@@ -657,14 +657,16 @@ public class MinimalPerfectHash<K> {
* A cryptographically weak hash function. It is supposed to be fast. * A cryptographically weak hash function. It is supposed to be fast.
* *
* @param o the string * @param o the string
* @param x the seed * @param index the hash function index
* @param seed the seed
* @return the hash value * @return the hash value
*/ */
public static int getFastHash(String o, int x) { public static int getFastHash(String o, int index, int seed) {
int result = o.length(); int x = (index * 0x9f3b) ^ seed;
int result = seed + o.length();
for (int i = 0; i < o.length(); i++) { for (int i = 0; i < o.length(); i++) {
x = 31 + x * 0x9f3b; x = 31 + x * 0x9f3b;
result += x * (1 + o.charAt(i)); result ^= x * (1 + o.charAt(i));
} }
return result; return result;
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论