| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.dev.hash; |
| 7 |
|
| 8 |
import java.io.ByteArrayOutputStream; |
| 9 |
import java.io.IOException; |
| 10 |
import java.nio.charset.StandardCharsets; |
| 11 |
import java.security.SecureRandom; |
| 12 |
import java.util.ArrayList; |
| 13 |
import java.util.Set; |
| 14 |
import java.util.concurrent.atomic.AtomicInteger; |
| 15 |
import java.util.concurrent.atomic.AtomicReference; |
| 16 |
import java.util.zip.Deflater; |
| 17 |
import java.util.zip.Inflater; |
| 18 |
|
| 19 |
/** |
| 20 |
* A minimal perfect hash function tool. It needs about 1.98 bits per key. |
| 21 |
* <p> |
| 22 |
* The algorithm is recursive: sets that contain no or only one entry are not |
| 23 |
* processed as no conflicts are possible. For sets that contain between 2 and |
| 24 |
* 12 entries, a number of hash functions are tested to check if they can store |
| 25 |
* the data without conflict. If no function was found, and for larger sets, the |
| 26 |
* set is split into a (possibly high) number of smaller set, which are |
| 27 |
* processed recursively. The average size of a top-level bucket is about 216 |
| 28 |
* entries, and the maximum recursion level is typically 5. |
| 29 |
* <p> |
| 30 |
* At the end of the generation process, the data is compressed using a general |
| 31 |
* purpose compression tool (Deflate / Huffman coding) down to 2.0 bits per key. |
| 32 |
* The uncompressed data is around 2.2 bits per key. With arithmetic coding, |
| 33 |
* about 1.9 bits per key are needed. Generating the hash function takes about |
| 34 |
* 2.5 seconds per million keys with 8 cores (multithreaded). The algorithm |
| 35 |
* automatically scales with the number of available CPUs (using as many threads |
| 36 |
* as there are processors). At the expense of processing time, a lower number |
| 37 |
* of bits per key would be possible (for example 1.84 bits per key with 100000 |
| 38 |
* keys, using 32 seconds generation time, with Huffman coding). |
| 39 |
* <p> |
| 40 |
* The memory usage to efficiently calculate hash values is around 2.5 bits per |
| 41 |
* key (the space needed for the uncompressed description, plus 8 bytes for |
| 42 |
* every top-level bucket). |
| 43 |
* <p> |
| 44 |
* At each level, only one user defined hash function per object is called |
| 45 |
* (about 3 hash functions per key). The result is further processed using a |
| 46 |
* supplemental hash function, so that the default user defined hash function |
| 47 |
* doesn't need to be sophisticated (it doesn't need to be non-linear, have a |
| 48 |
* good avalanche effect, or generate random looking data; it just should |
| 49 |
* produce few conflicts if possible). |
| 50 |
* <p> |
| 51 |
* To protect against hash flooding and similar attacks, a secure random seed |
| 52 |
* per hash table is used. For further protection, cryptographically secure |
| 53 |
* functions such as SipHash or SHA-256 can be used. However, such (slower) |
| 54 |
* functions only need to be used if regular hash functions produce too many |
| 55 |
* conflicts. This case is detected when generating the perfect hash function, |
| 56 |
* by checking if there are too many conflicts (more than 2160 entries in one |
| 57 |
* top-level bucket). In this case, the next hash function is used. That way, in |
| 58 |
* the normal case, where no attack is happening, only fast, but less secure, |
| 59 |
* hash functions are called. It is fine to use the regular hashCode method as |
| 60 |
* the level 0 hash function. However, just relying on the regular hashCode |
| 61 |
* method does not work if the key has more than 32 bits, because the risk of |
| 62 |
* collisions is too high. Incorrect universal hash functions are detected (an |
| 63 |
* exception is thrown if there are more than 32 recursion levels). |
| 64 |
* <p> |
| 65 |
* In-place updating of the hash table is not implemented but possible in |
| 66 |
* theory, by patching the hash function description. With a small change, |
| 67 |
* non-minimal perfect hash functions can be calculated (for example 1.22 bits |
| 68 |
* per key at a fill rate of 81%). |
| 69 |
* |
| 70 |
* @param <K> the key type |
| 71 |
*/ |
| 72 |
public class MinimalPerfectHash<K> { |
| 73 |
|
| 74 |
/** |
| 75 |
* Large buckets are typically divided into buckets of this size. |
| 76 |
*/ |
| 77 |
private static final int DIVIDE = 6; |
| 78 |
|
| 79 |
/** |
| 80 |
* For sets larger than this, instead of trying to map then uniquely to a |
| 81 |
* set of the same size, the size of the set is incremented by one. This |
| 82 |
* reduces the time to find a mapping, but the index of the hole also needs |
| 83 |
* to be stored, which increases the space usage. |
| 84 |
*/ |
| 85 |
private static final int SPEEDUP = 11; |
| 86 |
|
| 87 |
/** |
| 88 |
* The maximum size of a small bucket (one that is not further split if |
| 89 |
* possible). |
| 90 |
*/ |
| 91 |
private static final int MAX_SIZE = 14; |
| 92 |
|
| 93 |
/** |
| 94 |
* The maximum offset for hash functions of small buckets. At most that many |
| 95 |
* hash functions are tried for the given size. |
| 96 |
*/ |
| 97 |
private static final int[] MAX_OFFSETS = { 0, 0, 8, 18, 47, 123, 319, 831, 2162, |
| 98 |
5622, 14617, 38006, 98815, 256920, 667993 }; |
| 99 |
|
| 100 |
/** |
| 101 |
* The output value to split the bucket into many (more than 2) smaller |
| 102 |
* buckets. |
| 103 |
*/ |
| 104 |
private static final int SPLIT_MANY = 3; |
| 105 |
|
| 106 |
/** |
| 107 |
* The minimum output value for a small bucket of a given size. |
| 108 |
*/ |
| 109 |
private static final int[] SIZE_OFFSETS = new int[MAX_OFFSETS.length + 1]; |
| 110 |
|
| 111 |
/** |
| 112 |
* A secure random generator. |
| 113 |
*/ |
| 114 |
private static final SecureRandom RANDOM = new SecureRandom(); |
| 115 |
|
| 116 |
static { |
| 117 |
for (int i = SPEEDUP; i < MAX_OFFSETS.length; i++) { |
| 118 |
MAX_OFFSETS[i] = (int) (MAX_OFFSETS[i] * 2.5); |
| 119 |
} |
| 120 |
int last = SPLIT_MANY + 1; |
| 121 |
for (int i = 0; i < MAX_OFFSETS.length; i++) { |
| 122 |
SIZE_OFFSETS[i] = last; |
| 123 |
last += MAX_OFFSETS[i]; |
| 124 |
} |
| 125 |
SIZE_OFFSETS[SIZE_OFFSETS.length - 1] = last; |
| 126 |
} |
| 127 |
|
| 128 |
/** |
| 129 |
* The universal hash function. |
| 130 |
*/ |
| 131 |
private final UniversalHash<K> hash; |
| 132 |
|
| 133 |
/** |
| 134 |
* The description of the hash function. Used for calculating the hash of a |
| 135 |
* key. |
| 136 |
*/ |
| 137 |
private final byte[] data; |
| 138 |
|
| 139 |
/** |
| 140 |
* The random seed. |
| 141 |
*/ |
| 142 |
private final int seed; |
| 143 |
|
| 144 |
/** |
| 145 |
* The size up to the given root-level bucket in the data array. Used to |
| 146 |
* speed up calculating the hash of a key. |
| 147 |
*/ |
| 148 |
private final int[] rootSize; |
| 149 |
|
| 150 |
/** |
| 151 |
* The position of the given root-level bucket in the data array. Used to |
| 152 |
* speed up calculating the hash of a key. |
| 153 |
*/ |
| 154 |
private final int[] rootPos; |
| 155 |
|
| 156 |
/** |
| 157 |
* The hash function level at the root of the tree. Typically 0, except if |
| 158 |
* the hash function at that level didn't split the entries as expected |
| 159 |
* (which can be due to a bad hash function, or due to an attack). |
| 160 |
*/ |
| 161 |
private final int rootLevel; |
| 162 |
|
| 163 |
/** |
| 164 |
* Create a hash object to convert keys to hashes. |
| 165 |
* |
| 166 |
* @param desc the data returned by the generate method |
| 167 |
* @param hash the universal hash function |
| 168 |
*/ |
| 169 |
public MinimalPerfectHash(byte[] desc, UniversalHash<K> hash) { |
| 170 |
this.hash = hash; |
| 171 |
byte[] b = data = expand(desc); |
| 172 |
seed = ((b[0] & 255) << 24) | |
| 173 |
((b[1] & 255) << 16) | |
| 174 |
((b[2] & 255) << 8) | |
| 175 |
(b[3] & 255); |
| 176 |
if (b[4] == SPLIT_MANY) { |
| 177 |
rootLevel = b[b.length - 1] & 255; |
| 178 |
int split = readVarInt(b, 5); |
| 179 |
rootSize = new int[split]; |
| 180 |
rootPos = new int[split]; |
| 181 |
int pos = 5 + getVarIntLength(b, 5); |
| 182 |
int sizeSum = 0; |
| 183 |
for (int i = 0; i < split; i++) { |
| 184 |
rootSize[i] = sizeSum; |
| 185 |
rootPos[i] = pos; |
| 186 |
int start = pos; |
| 187 |
pos = getNextPos(pos); |
| 188 |
sizeSum += getSizeSum(start, pos); |
| 189 |
} |
| 190 |
} else { |
| 191 |
rootLevel = 0; |
| 192 |
rootSize = null; |
| 193 |
rootPos = null; |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
/** |
| 198 |
* Calculate the hash value for the given key. |
| 199 |
* |
| 200 |
* @param x the key |
| 201 |
* @return the hash value |
| 202 |
*/ |
| 203 |
public int get(K x) { |
| 204 |
return get(4, x, true, rootLevel); |
| 205 |
} |
| 206 |
|
| 207 |
/** |
| 208 |
* Get the hash value for the given key, starting at a certain position and |
| 209 |
* level. |
| 210 |
* |
| 211 |
* @param pos the start position |
| 212 |
* @param x the key |
| 213 |
* @param isRoot whether this is the root of the tree |
| 214 |
* @param level the level |
| 215 |
* @return the hash value |
| 216 |
*/ |
| 217 |
private int get(int pos, K x, boolean isRoot, int level) { |
| 218 |
int n = readVarInt(data, pos); |
| 219 |
if (n < 2) { |
| 220 |
return 0; |
| 221 |
} else if (n > SPLIT_MANY) { |
| 222 |
int size = getSize(n); |
| 223 |
int offset = getOffset(n, size); |
| 224 |
if (size >= SPEEDUP) { |
| 225 |
int p = offset % (size + 1); |
| 226 |
offset = offset / (size + 1); |
| 227 |
int result = hash(x, hash, level, seed, offset, size + 1); |
| 228 |
if (result >= p) { |
| 229 |
result--; |
| 230 |
} |
| 231 |
return result; |
| 232 |
} |
| 233 |
return hash(x, hash, level, seed, offset, size); |
| 234 |
} |
| 235 |
pos++; |
| 236 |
int split; |
| 237 |
if (n == SPLIT_MANY) { |
| 238 |
split = readVarInt(data, pos); |
| 239 |
pos += getVarIntLength(data, pos); |
| 240 |
} else { |
| 241 |
split = n; |
| 242 |
} |
| 243 |
int h = hash(x, hash, level, seed, 0, split); |
| 244 |
int s; |
| 245 |
if (isRoot && rootPos != null) { |
| 246 |
s = rootSize[h]; |
| 247 |
pos = rootPos[h]; |
| 248 |
} else { |
| 249 |
int start = pos; |
| 250 |
for (int i = 0; i < h; i++) { |
| 251 |
pos = getNextPos(pos); |
| 252 |
} |
| 253 |
s = getSizeSum(start, pos); |
| 254 |
} |
| 255 |
return s + get(pos, x, false, level + 1); |
| 256 |
} |
| 257 |
|
| 258 |
/** |
| 259 |
* Get the position of the next sibling. |
| 260 |
* |
| 261 |
* @param pos the position of this branch |
| 262 |
* @return the position of the next sibling |
| 263 |
*/ |
| 264 |
private int getNextPos(int pos) { |
| 265 |
int n = readVarInt(data, pos); |
| 266 |
pos += getVarIntLength(data, pos); |
| 267 |
if (n < 2 || n > SPLIT_MANY) { |
| 268 |
return pos; |
| 269 |
} |
| 270 |
int split; |
| 271 |
if (n == SPLIT_MANY) { |
| 272 |
split = readVarInt(data, pos); |
| 273 |
pos += getVarIntLength(data, pos); |
| 274 |
} else { |
| 275 |
split = n; |
| 276 |
} |
| 277 |
for (int i = 0; i < split; i++) { |
| 278 |
pos = getNextPos(pos); |
| 279 |
} |
| 280 |
return pos; |
| 281 |
} |
| 282 |
|
| 283 |
/** |
| 284 |
* The sum of the sizes between the start and end position. |
| 285 |
* |
| 286 |
* @param start the start position |
| 287 |
* @param end the end position (excluding) |
| 288 |
* @return the sizes |
| 289 |
*/ |
| 290 |
private int getSizeSum(int start, int end) { |
| 291 |
int s = 0; |
| 292 |
for (int pos = start; pos < end;) { |
| 293 |
int n = readVarInt(data, pos); |
| 294 |
pos += getVarIntLength(data, pos); |
| 295 |
if (n < 2) { |
| 296 |
s += n; |
| 297 |
} else if (n > SPLIT_MANY) { |
| 298 |
s += getSize(n); |
| 299 |
} else if (n == SPLIT_MANY) { |
| 300 |
pos += getVarIntLength(data, pos); |
| 301 |
} |
| 302 |
} |
| 303 |
return s; |
| 304 |
} |
| 305 |
|
| 306 |
private static void writeSizeOffset(ByteArrayOutputStream out, int size, |
| 307 |
int offset) { |
| 308 |
writeVarInt(out, SIZE_OFFSETS[size] + offset); |
| 309 |
} |
| 310 |
|
| 311 |
private static int getOffset(int n, int size) { |
| 312 |
return n - SIZE_OFFSETS[size]; |
| 313 |
} |
| 314 |
|
| 315 |
private static int getSize(int n) { |
| 316 |
for (int i = 0; i < SIZE_OFFSETS.length; i++) { |
| 317 |
if (n < SIZE_OFFSETS[i]) { |
| 318 |
return i - 1; |
| 319 |
} |
| 320 |
} |
| 321 |
return 0; |
| 322 |
} |
| 323 |
|
| 324 |
/** |
| 325 |
* Generate the minimal perfect hash function data from the given set of |
| 326 |
* integers. |
| 327 |
* |
| 328 |
* @param set the data |
| 329 |
* @param hash the universal hash function |
| 330 |
* @return the hash function description |
| 331 |
*/ |
| 332 |
public static <K> byte[] generate(Set<K> set, UniversalHash<K> hash) { |
| 333 |
ArrayList<K> list = new ArrayList<>(set); |
| 334 |
ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 335 |
int seed = RANDOM.nextInt(); |
| 336 |
out.write(seed >>> 24); |
| 337 |
out.write(seed >>> 16); |
| 338 |
out.write(seed >>> 8); |
| 339 |
out.write(seed); |
| 340 |
generate(list, hash, 0, seed, out); |
| 341 |
return compress(out.toByteArray()); |
| 342 |
} |
| 343 |
|
| 344 |
/** |
| 345 |
* Generate the perfect hash function data from the given set of integers. |
| 346 |
* |
| 347 |
* @param list the data, in the form of a list |
| 348 |
* @param hash the universal hash function |
| 349 |
* @param level the recursion level |
| 350 |
* @param seed the random seed |
| 351 |
* @param out the output stream |
| 352 |
*/ |
| 353 |
static <K> void generate(ArrayList<K> list, UniversalHash<K> hash, |
| 354 |
int level, int seed, ByteArrayOutputStream out) { |
| 355 |
int size = list.size(); |
| 356 |
if (size <= 1) { |
| 357 |
out.write(size); |
| 358 |
return; |
| 359 |
} |
| 360 |
if (level > 32) { |
| 361 |
throw new IllegalStateException("Too many recursions; " + |
| 362 |
" incorrect universal hash function?"); |
| 363 |
} |
| 364 |
if (size <= MAX_SIZE) { |
| 365 |
int maxOffset = MAX_OFFSETS[size]; |
| 366 |
// get the hash codes - we could stop early |
| 367 |
// if we detect that two keys have the same hash |
| 368 |
int[] hashes = new int[size]; |
| 369 |
for (int i = 0; i < size; i++) { |
| 370 |
hashes[i] = hash.hashCode(list.get(i), level, seed); |
| 371 |
} |
| 372 |
// use the supplemental hash function to find a way |
| 373 |
// to make the hash code unique within this group - |
| 374 |
// there might be a much faster way than that, by |
| 375 |
// checking which bits of the hash code matter most |
| 376 |
int testSize = size; |
| 377 |
if (size >= SPEEDUP) { |
| 378 |
testSize++; |
| 379 |
maxOffset /= testSize; |
| 380 |
} |
| 381 |
nextOffset: |
| 382 |
for (int offset = 0; offset < maxOffset; offset++) { |
| 383 |
int bits = 0; |
| 384 |
for (int i = 0; i < size; i++) { |
| 385 |
int x = hashes[i]; |
| 386 |
int h = hash(x, level, offset, testSize); |
| 387 |
if ((bits & (1 << h)) != 0) { |
| 388 |
continue nextOffset; |
| 389 |
} |
| 390 |
bits |= 1 << h; |
| 391 |
} |
| 392 |
if (size >= SPEEDUP) { |
| 393 |
int pos = Integer.numberOfTrailingZeros(~bits); |
| 394 |
writeSizeOffset(out, size, offset * (size + 1) + pos); |
| 395 |
} else { |
| 396 |
writeSizeOffset(out, size, offset); |
| 397 |
} |
| 398 |
return; |
| 399 |
} |
| 400 |
} |
| 401 |
int split; |
| 402 |
if (size > 57 * DIVIDE) { |
| 403 |
split = size / (36 * DIVIDE); |
| 404 |
} else { |
| 405 |
split = (size - 47) / DIVIDE; |
| 406 |
} |
| 407 |
split = Math.max(2, split); |
| 408 |
boolean isRoot = level == 0; |
| 409 |
ArrayList<ArrayList<K>> lists; |
| 410 |
do { |
| 411 |
lists = new ArrayList<>(split); |
| 412 |
for (int i = 0; i < split; i++) { |
| 413 |
lists.add(new ArrayList<K>(size / split)); |
| 414 |
} |
| 415 |
for (int i = 0; i < size; i++) { |
| 416 |
K x = list.get(i); |
| 417 |
ArrayList<K> l = lists.get(hash(x, hash, level, seed, 0, split)); |
| 418 |
l.add(x); |
| 419 |
if (isRoot && split >= SPLIT_MANY && |
| 420 |
l.size() > 36 * DIVIDE * 10) { |
| 421 |
// a bad hash function or attack was detected |
| 422 |
level++; |
| 423 |
lists = null; |
| 424 |
break; |
| 425 |
} |
| 426 |
} |
| 427 |
} while (lists == null); |
| 428 |
if (split >= SPLIT_MANY) { |
| 429 |
out.write(SPLIT_MANY); |
| 430 |
} |
| 431 |
writeVarInt(out, split); |
| 432 |
boolean multiThreaded = isRoot && list.size() > 1000; |
| 433 |
list.clear(); |
| 434 |
list.trimToSize(); |
| 435 |
if (multiThreaded) { |
| 436 |
generateMultiThreaded(lists, hash, level, seed, out); |
| 437 |
} else { |
| 438 |
for (ArrayList<K> s2 : lists) { |
| 439 |
generate(s2, hash, level + 1, seed, out); |
| 440 |
} |
| 441 |
} |
| 442 |
if (isRoot && split >= SPLIT_MANY) { |
| 443 |
out.write(level); |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
private static <K> void generateMultiThreaded( |
| 448 |
final ArrayList<ArrayList<K>> lists, |
| 449 |
final UniversalHash<K> hash, |
| 450 |
final int level, |
| 451 |
final int seed, |
| 452 |
ByteArrayOutputStream out) { |
| 453 |
final ArrayList<ByteArrayOutputStream> outList = |
| 454 |
new ArrayList<>(); |
| 455 |
int processors = Runtime.getRuntime().availableProcessors(); |
| 456 |
Thread[] threads = new Thread[processors]; |
| 457 |
final AtomicInteger success = new AtomicInteger(); |
| 458 |
final AtomicReference<Exception> failure = new AtomicReference<>(); |
| 459 |
for (int i = 0; i < processors; i++) { |
| 460 |
threads[i] = new Thread() { |
| 461 |
@Override |
| 462 |
public void run() { |
| 463 |
try { |
| 464 |
while (true) { |
| 465 |
ArrayList<K> list; |
| 466 |
ByteArrayOutputStream temp = |
| 467 |
new ByteArrayOutputStream(); |
| 468 |
synchronized (lists) { |
| 469 |
if (lists.isEmpty()) { |
| 470 |
break; |
| 471 |
} |
| 472 |
list = lists.remove(0); |
| 473 |
outList.add(temp); |
| 474 |
} |
| 475 |
generate(list, hash, level + 1, seed, temp); |
| 476 |
} |
| 477 |
} catch (Exception e) { |
| 478 |
failure.set(e); |
| 479 |
return; |
| 480 |
} |
| 481 |
success.incrementAndGet(); |
| 482 |
} |
| 483 |
}; |
| 484 |
} |
| 485 |
for (Thread t : threads) { |
| 486 |
t.start(); |
| 487 |
} |
| 488 |
try { |
| 489 |
for (Thread t : threads) { |
| 490 |
t.join(); |
| 491 |
} |
| 492 |
if (success.get() != threads.length) { |
| 493 |
Exception e = failure.get(); |
| 494 |
if (e != null) { |
| 495 |
throw new RuntimeException(e); |
| 496 |
} |
| 497 |
throw new RuntimeException("Unknown failure in one thread"); |
| 498 |
} |
| 499 |
for (ByteArrayOutputStream temp : outList) { |
| 500 |
out.write(temp.toByteArray()); |
| 501 |
} |
| 502 |
} catch (InterruptedException | IOException e) { |
| 503 |
throw new RuntimeException(e); |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
/** |
| 508 |
* Calculate the hash of a key. The result depends on the key, the recursion |
| 509 |
* level, and the offset. |
| 510 |
* |
| 511 |
* @param o the key |
| 512 |
* @param level the recursion level |
| 513 |
* @param seed the random seed |
| 514 |
* @param offset the index of the hash function |
| 515 |
* @param size the size of the bucket |
| 516 |
* @return the hash (a value between 0, including, and the size, excluding) |
| 517 |
*/ |
| 518 |
private static <K> int hash(K o, UniversalHash<K> hash, int level, |
| 519 |
int seed, int offset, int size) { |
| 520 |
int x = hash.hashCode(o, level, seed); |
| 521 |
x += level + offset * 32; |
| 522 |
x = ((x >>> 16) ^ x) * 0x45d9f3b; |
| 523 |
x = ((x >>> 16) ^ x) * 0x45d9f3b; |
| 524 |
x = (x >>> 16) ^ x; |
| 525 |
return (x & (-1 >>> 1)) % size; |
| 526 |
} |
| 527 |
|
| 528 |
private static int hash(int x, int level, int offset, int size) { |
| 529 |
x += level + offset * 32; |
| 530 |
x = ((x >>> 16) ^ x) * 0x45d9f3b; |
| 531 |
x = ((x >>> 16) ^ x) * 0x45d9f3b; |
| 532 |
x = (x >>> 16) ^ x; |
| 533 |
return (x & (-1 >>> 1)) % size; |
| 534 |
} |
| 535 |
|
| 536 |
private static int writeVarInt(ByteArrayOutputStream out, int x) { |
| 537 |
int len = 0; |
| 538 |
while ((x & ~0x7f) != 0) { |
| 539 |
out.write((byte) (0x80 | (x & 0x7f))); |
| 540 |
x >>>= 7; |
| 541 |
len++; |
| 542 |
} |
| 543 |
out.write((byte) x); |
| 544 |
return ++len; |
| 545 |
} |
| 546 |
|
| 547 |
private static int readVarInt(byte[] d, int pos) { |
| 548 |
int x = d[pos++]; |
| 549 |
if (x >= 0) { |
| 550 |
return x; |
| 551 |
} |
| 552 |
x &= 0x7f; |
| 553 |
for (int s = 7; s < 64; s += 7) { |
| 554 |
int b = d[pos++]; |
| 555 |
x |= (b & 0x7f) << s; |
| 556 |
if (b >= 0) { |
| 557 |
break; |
| 558 |
} |
| 559 |
} |
| 560 |
return x; |
| 561 |
} |
| 562 |
|
| 563 |
private static int getVarIntLength(byte[] d, int pos) { |
| 564 |
int x = d[pos++]; |
| 565 |
if (x >= 0) { |
| 566 |
return 1; |
| 567 |
} |
| 568 |
int len = 2; |
| 569 |
for (int s = 7; s < 64; s += 7) { |
| 570 |
int b = d[pos++]; |
| 571 |
if (b >= 0) { |
| 572 |
break; |
| 573 |
} |
| 574 |
len++; |
| 575 |
} |
| 576 |
return len; |
| 577 |
} |
| 578 |
|
| 579 |
/** |
| 580 |
* Compress the hash description using a Huffman coding. |
| 581 |
* |
| 582 |
* @param d the data |
| 583 |
* @return the compressed data |
| 584 |
*/ |
| 585 |
private static byte[] compress(byte[] d) { |
| 586 |
Deflater deflater = new Deflater(); |
| 587 |
deflater.setStrategy(Deflater.HUFFMAN_ONLY); |
| 588 |
deflater.setInput(d); |
| 589 |
deflater.finish(); |
| 590 |
ByteArrayOutputStream out2 = new ByteArrayOutputStream(d.length); |
| 591 |
byte[] buffer = new byte[1024]; |
| 592 |
while (!deflater.finished()) { |
| 593 |
int count = deflater.deflate(buffer); |
| 594 |
out2.write(buffer, 0, count); |
| 595 |
} |
| 596 |
deflater.end(); |
| 597 |
return out2.toByteArray(); |
| 598 |
} |
| 599 |
|
| 600 |
/** |
| 601 |
* Decompress the hash description using a Huffman coding. |
| 602 |
* |
| 603 |
* @param d the data |
| 604 |
* @return the decompressed data |
| 605 |
*/ |
| 606 |
private static byte[] expand(byte[] d) { |
| 607 |
Inflater inflater = new Inflater(); |
| 608 |
inflater.setInput(d); |
| 609 |
ByteArrayOutputStream out = new ByteArrayOutputStream(d.length); |
| 610 |
byte[] buffer = new byte[1024]; |
| 611 |
try { |
| 612 |
while (!inflater.finished()) { |
| 613 |
int count = inflater.inflate(buffer); |
| 614 |
out.write(buffer, 0, count); |
| 615 |
} |
| 616 |
inflater.end(); |
| 617 |
} catch (Exception e) { |
| 618 |
throw new IllegalArgumentException(e); |
| 619 |
} |
| 620 |
return out.toByteArray(); |
| 621 |
} |
| 622 |
|
| 623 |
/** |
| 624 |
* An interface that can calculate multiple hash values for an object. The |
| 625 |
* returned hash value of two distinct objects may be the same for a given |
| 626 |
* hash function index, but as more hash functions indexes are called for |
| 627 |
* those objects, the returned value must eventually be different. |
| 628 |
* <p> |
| 629 |
* The returned value does not need to be uniformly distributed. |
| 630 |
* |
| 631 |
* @param <T> the type |
| 632 |
*/ |
| 633 |
public interface UniversalHash<T> { |
| 634 |
|
| 635 |
/** |
| 636 |
* Calculate the hash of the given object. |
| 637 |
* |
| 638 |
* @param o the object |
| 639 |
* @param index the hash function index (index 0 is used first, so the |
| 640 |
* method should be very fast with index 0; index 1 and so on |
| 641 |
* are only called when really needed) |
| 642 |
* @param seed the random seed (always the same for a hash table) |
| 643 |
* @return the hash value |
| 644 |
*/ |
| 645 |
int hashCode(T o, int index, int seed); |
| 646 |
|
| 647 |
} |
| 648 |
|
| 649 |
/** |
| 650 |
* A sample hash implementation for long keys. |
| 651 |
*/ |
| 652 |
public static class LongHash implements UniversalHash<Long> { |
| 653 |
|
| 654 |
@Override |
| 655 |
public int hashCode(Long o, int index, int seed) { |
| 656 |
if (index == 0) { |
| 657 |
return o.hashCode(); |
| 658 |
} else if (index < 8) { |
| 659 |
long x = o; |
| 660 |
x += index; |
| 661 |
x = ((x >>> 32) ^ x) * 0x45d9f3b; |
| 662 |
x = ((x >>> 32) ^ x) * 0x45d9f3b; |
| 663 |
return (int) (x ^ (x >>> 32)); |
| 664 |
} |
| 665 |
// get the lower or higher 32 bit depending on the index |
| 666 |
int shift = (index & 1) * 32; |
| 667 |
return (int) (o >>> shift); |
| 668 |
} |
| 669 |
|
| 670 |
} |
| 671 |
|
| 672 |
/** |
| 673 |
* A sample hash implementation for integer keys. |
| 674 |
*/ |
| 675 |
public static class StringHash implements UniversalHash<String> { |
| 676 |
|
| 677 |
@Override |
| 678 |
public int hashCode(String o, int index, int seed) { |
| 679 |
if (index == 0) { |
| 680 |
// use the default hash of a string, which might already be |
| 681 |
// available |
| 682 |
return o.hashCode(); |
| 683 |
} else if (index < 8) { |
| 684 |
// use a different hash function, which is fast but not |
| 685 |
// necessarily universal, and not cryptographically secure |
| 686 |
return getFastHash(o, index, seed); |
| 687 |
} |
| 688 |
// this method is supposed to be cryptographically secure; |
| 689 |
// we could use SHA-256 for higher indexes |
| 690 |
return getSipHash24(o, index, seed); |
| 691 |
} |
| 692 |
|
| 693 |
/** |
| 694 |
* A cryptographically weak hash function. It is supposed to be fast. |
| 695 |
* |
| 696 |
* @param o the string |
| 697 |
* @param index the hash function index |
| 698 |
* @param seed the seed |
| 699 |
* @return the hash value |
| 700 |
*/ |
| 701 |
public static int getFastHash(String o, int index, int seed) { |
| 702 |
int x = (index * 0x9f3b) ^ seed; |
| 703 |
int result = seed + o.length(); |
| 704 |
for (int i = 0; i < o.length(); i++) { |
| 705 |
x = 31 + x * 0x9f3b; |
| 706 |
result ^= x * (1 + o.charAt(i)); |
| 707 |
} |
| 708 |
return result; |
| 709 |
} |
| 710 |
|
| 711 |
/** |
| 712 |
* A cryptographically relatively secure hash function. It is supposed |
| 713 |
* to protected against hash-flooding denial-of-service attacks. |
| 714 |
* |
| 715 |
* @param o the string |
| 716 |
* @param k0 key 0 |
| 717 |
* @param k1 key 1 |
| 718 |
* @return the hash value |
| 719 |
*/ |
| 720 |
public static int getSipHash24(String o, long k0, long k1) { |
| 721 |
byte[] b = o.getBytes(StandardCharsets.UTF_8); |
| 722 |
return getSipHash24(b, 0, b.length, k0, k1); |
| 723 |
} |
| 724 |
|
| 725 |
/** |
| 726 |
* A cryptographically relatively secure hash function. It is supposed |
| 727 |
* to protected against hash-flooding denial-of-service attacks. |
| 728 |
* |
| 729 |
* @param b the data |
| 730 |
* @param start the start position |
| 731 |
* @param end the end position plus one |
| 732 |
* @param k0 key 0 |
| 733 |
* @param k1 key 1 |
| 734 |
* @return the hash value |
| 735 |
*/ |
| 736 |
public static int getSipHash24(byte[] b, int start, int end, long k0, long k1) { |
| 737 |
long v0 = k0 ^ 0x736f6d6570736575L; |
| 738 |
long v1 = k1 ^ 0x646f72616e646f6dL; |
| 739 |
long v2 = k0 ^ 0x6c7967656e657261L; |
| 740 |
long v3 = k1 ^ 0x7465646279746573L; |
| 741 |
int repeat; |
| 742 |
for (int off = start; off <= end + 8; off += 8) { |
| 743 |
long m; |
| 744 |
if (off <= end) { |
| 745 |
m = 0; |
| 746 |
int i = 0; |
| 747 |
for (; i < 8 && off + i < end; i++) { |
| 748 |
m |= ((long) b[off + i] & 255) << (8 * i); |
| 749 |
} |
| 750 |
if (i < 8) { |
| 751 |
m |= ((long) end - start) << 56; |
| 752 |
} |
| 753 |
v3 ^= m; |
| 754 |
repeat = 2; |
| 755 |
} else { |
| 756 |
m = 0; |
| 757 |
v2 ^= 0xff; |
| 758 |
repeat = 4; |
| 759 |
} |
| 760 |
for (int i = 0; i < repeat; i++) { |
| 761 |
v0 += v1; |
| 762 |
v2 += v3; |
| 763 |
v1 = Long.rotateLeft(v1, 13); |
| 764 |
v3 = Long.rotateLeft(v3, 16); |
| 765 |
v1 ^= v0; |
| 766 |
v3 ^= v2; |
| 767 |
v0 = Long.rotateLeft(v0, 32); |
| 768 |
v2 += v1; |
| 769 |
v0 += v3; |
| 770 |
v1 = Long.rotateLeft(v1, 17); |
| 771 |
v3 = Long.rotateLeft(v3, 21); |
| 772 |
v1 ^= v2; |
| 773 |
v3 ^= v0; |
| 774 |
v2 = Long.rotateLeft(v2, 32); |
| 775 |
} |
| 776 |
v0 ^= m; |
| 777 |
} |
| 778 |
return (int) (v0 ^ v1 ^ v2 ^ v3); |
| 779 |
} |
| 780 |
|
| 781 |
} |
| 782 |
|
| 783 |
} |