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

Better (non-universal) fast hash function

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