/
Hashing.java
847 lines (777 loc) · 32.3 KB
/
Hashing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static java.lang.invoke.MethodType.methodType;
import com.google.errorprone.annotations.Immutable;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.security.Key;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.annotation.CheckForNull;
import javax.crypto.spec.SecretKeySpec;
/**
* Static methods to obtain {@link HashFunction} instances, and other static hashing-related
* utilities.
*
* <p>A comparison of the various hash functions can be found <a
* href="http://goo.gl/jS7HH">here</a>.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
* @since 11.0
*/
@ElementTypesAreNonnullByDefault
public final class Hashing {
/**
* Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm
* the returned function implements is unspecified and subject to change without notice.
*
* <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code
* Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current
* process in any way, for example being sent over RPC, or saved to disk. For a general-purpose,
* non-cryptographic hash function that will never change behavior, we suggest {@link
* #murmur3_128}.
*
* <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value
* for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances.
*
* @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link
* HashFunction} instance may use memory proportional to this integer.
* @return a hash function, described above, that produces hash codes of length {@code
* minimumBits} or greater
*/
public static HashFunction goodFastHash(int minimumBits) {
int bits = checkPositiveAndMakeMultipleOf32(minimumBits);
if (bits == 32) {
return Murmur3_32HashFunction.GOOD_FAST_HASH_32;
}
if (bits <= 128) {
return Murmur3_128HashFunction.GOOD_FAST_HASH_128;
}
// Otherwise, join together some 128-bit murmur3s
int hashFunctionsNeeded = (bits + 127) / 128;
HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded];
hashFunctions[0] = Murmur3_128HashFunction.GOOD_FAST_HASH_128;
int seed = GOOD_FAST_HASH_SEED;
for (int i = 1; i < hashFunctionsNeeded; i++) {
seed += 1500450271; // a prime; shouldn't matter
hashFunctions[i] = murmur3_128(seed);
}
return new ConcatenatedHashFunction(hashFunctions);
}
/**
* Used to randomize {@link #goodFastHash} instances, so that programs which persist anything
* dependent on the hash codes they produce will fail sooner.
*/
@SuppressWarnings("GoodTime") // reading system time without TimeSource
static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis();
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known
* bug</b> as described in the deprecation text.
*
* <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not
* have the bug.
*
* @deprecated This implementation produces incorrect hash values from the {@link
* HashFunction#hashString} method if the string contains non-BMP characters. Use {@link
* #murmur3_32_fixed(int)} instead.
*/
@Deprecated
public static HashFunction murmur3_32(int seed) {
return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ false);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known
* bug</b> as described in the deprecation text.
*
* <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not
* have the bug.
*
* @deprecated This implementation produces incorrect hash values from the {@link
* HashFunction#hashString} method if the string contains non-BMP characters. Use {@link
* #murmur3_32_fixed()} instead.
*/
@Deprecated
public static HashFunction murmur3_32() {
return Murmur3_32HashFunction.MURMUR3_32;
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value.
*
* <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A).
*
* <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code
* HashFunction} returned by the original {@code murmur3_32} method.
*
* @since 31.0
*/
public static HashFunction murmur3_32_fixed(int seed) {
return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ true);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using a seed value of zero.
*
* <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A).
*
* <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code
* HashFunction} returned by the original {@code murmur3_32} method.
*
* @since 31.0
*/
public static HashFunction murmur3_32_fixed() {
return Murmur3_32HashFunction.MURMUR3_32_FIXED;
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3
* algorithm, x64 variant</a> (little-endian variant), using the given seed value.
*
* <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F).
*/
public static HashFunction murmur3_128(int seed) {
return new Murmur3_128HashFunction(seed);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3
* algorithm, x64 variant</a> (little-endian variant), using a seed value of zero.
*
* <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F).
*/
public static HashFunction murmur3_128() {
return Murmur3_128HashFunction.MURMUR3_128;
}
/**
* Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit
* SipHash-2-4 algorithm</a> using a seed value of {@code k = 00 01 02 ...}.
*
* @since 15.0
*/
public static HashFunction sipHash24() {
return SipHashFunction.SIP_HASH_24;
}
/**
* Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit
* SipHash-2-4 algorithm</a> using the given seed.
*
* @since 15.0
*/
public static HashFunction sipHash24(long k0, long k1) {
return new SipHashFunction(2, 4, k0, k1);
}
/**
* Returns a hash function implementing the MD5 hash algorithm (128 hash bits).
*
* @deprecated If you must interoperate with a system that requires MD5, then use this method,
* despite its deprecation. But if you can choose your hash function, avoid MD5, which is
* neither fast nor secure. As of January 2017, we suggest:
* <ul>
* <li>For security:
* {@link Hashing#sha256} or a higher-level API.
* <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats.
* </ul>
*/
@Deprecated
public static HashFunction md5() {
return Md5Holder.MD5;
}
private static class Md5Holder {
static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()");
}
/**
* Returns a hash function implementing the SHA-1 algorithm (160 hash bits).
*
* @deprecated If you must interoperate with a system that requires SHA-1, then use this method,
* despite its deprecation. But if you can choose your hash function, avoid SHA-1, which is
* neither fast nor secure. As of January 2017, we suggest:
* <ul>
* <li>For security:
* {@link Hashing#sha256} or a higher-level API.
* <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats.
* </ul>
*/
@Deprecated
public static HashFunction sha1() {
return Sha1Holder.SHA_1;
}
private static class Sha1Holder {
static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()");
}
/** Returns a hash function implementing the SHA-256 algorithm (256 hash bits). */
public static HashFunction sha256() {
return Sha256Holder.SHA_256;
}
private static class Sha256Holder {
static final HashFunction SHA_256 =
new MessageDigestHashFunction("SHA-256", "Hashing.sha256()");
}
/**
* Returns a hash function implementing the SHA-384 algorithm (384 hash bits).
*
* @since 19.0
*/
public static HashFunction sha384() {
return Sha384Holder.SHA_384;
}
private static class Sha384Holder {
static final HashFunction SHA_384 =
new MessageDigestHashFunction("SHA-384", "Hashing.sha384()");
}
/** Returns a hash function implementing the SHA-512 algorithm (512 hash bits). */
public static HashFunction sha512() {
return Sha512Holder.SHA_512;
}
private static class Sha512Holder {
static final HashFunction SHA_512 =
new MessageDigestHashFunction("SHA-512", "Hashing.sha512()");
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* MD5 (128 hash bits) hash function and the given secret key.
*
* <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other
* future-proof algorithms <a
* href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacMd5(Key key) {
return new MacHashFunction("HmacMD5", key, hmacToString("hmacMd5", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* MD5 (128 hash bits) hash function and a {@link SecretKeySpec} created from the given byte array
* and the MD5 algorithm.
*
* <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other
* future-proof algorithms <a
* href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacMd5(byte[] key) {
return hmacMd5(new SecretKeySpec(checkNotNull(key), "HmacMD5"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-1 (160 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha1(Key key) {
return new MacHashFunction("HmacSHA1", key, hmacToString("hmacSha1", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-1 (160 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-1 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha1(byte[] key) {
return hmacSha1(new SecretKeySpec(checkNotNull(key), "HmacSHA1"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-256 (256 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha256(Key key) {
return new MacHashFunction("HmacSHA256", key, hmacToString("hmacSha256", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-256 (256 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-256 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha256(byte[] key) {
return hmacSha256(new SecretKeySpec(checkNotNull(key), "HmacSHA256"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-512 (512 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha512(Key key) {
return new MacHashFunction("HmacSHA512", key, hmacToString("hmacSha512", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-512 (512 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-512 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha512(byte[] key) {
return hmacSha512(new SecretKeySpec(checkNotNull(key), "HmacSHA512"));
}
private static String hmacToString(String methodName, Key key) {
return "Hashing."
+ methodName
+ "(Key[algorithm="
+ key.getAlgorithm()
+ ", format="
+ key.getFormat()
+ "])";
}
/**
* Returns a hash function implementing the CRC32C checksum algorithm (32 hash bits) as described
* by RFC 3720, Section 12.1.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 18.0
*/
public static HashFunction crc32c() {
return Crc32CSupplier.HASH_FUNCTION;
}
@Immutable
private enum Crc32CSupplier implements ImmutableSupplier<HashFunction> {
@J2ObjCIncompatible
JAVA_UTIL_ZIP {
@Override
public HashFunction get() {
return ChecksumType.CRC_32C.hashFunction;
}
},
ABSTRACT_HASH_FUNCTION {
@Override
public HashFunction get() {
return Crc32cHashFunction.CRC_32_C;
}
};
static final HashFunction HASH_FUNCTION = pickFunction().get();
private static Crc32CSupplier pickFunction() {
Crc32CSupplier[] functions = values();
if (functions.length == 1) {
// We're running under J2ObjC.
return functions[0];
}
// We can't refer to JAVA_UTIL_ZIP directly at compile time because of J2ObjC.
Crc32CSupplier javaUtilZip = functions[0];
try {
Class.forName("java.util.zip.CRC32C");
return javaUtilZip;
} catch (ClassNotFoundException runningUnderJava8) {
return ABSTRACT_HASH_FUNCTION;
}
}
}
/**
* Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits).
*
* <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code
* HashCode} produced by this function, use {@link HashCode#padToLong()}.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 14.0
*/
public static HashFunction crc32() {
return ChecksumType.CRC_32.hashFunction;
}
/**
* Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits).
*
* <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code
* HashCode} produced by this function, use {@link HashCode#padToLong()}.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 14.0
*/
public static HashFunction adler32() {
return ChecksumType.ADLER_32.hashFunction;
}
@Immutable
enum ChecksumType implements ImmutableSupplier<Checksum> {
CRC_32("Hashing.crc32()") {
@Override
public Checksum get() {
return new CRC32();
}
},
@J2ObjCIncompatible
CRC_32C("Hashing.crc32c()") {
@Override
public Checksum get() {
return Crc32cMethodHandles.newCrc32c();
}
},
ADLER_32("Hashing.adler32()") {
@Override
public Checksum get() {
return new Adler32();
}
};
public final HashFunction hashFunction;
ChecksumType(String toString) {
this.hashFunction = new ChecksumHashFunction(this, 32, toString);
}
}
@J2ObjCIncompatible
@SuppressWarnings("unused")
private static final class Crc32cMethodHandles {
private static final MethodHandle CONSTRUCTOR = crc32cConstructor();
@IgnoreJRERequirement // https://github.com/mojohaus/animal-sniffer/issues/67
static Checksum newCrc32c() {
try {
return (Checksum) CONSTRUCTOR.invokeExact();
} catch (Throwable e) {
throwIfUnchecked(e);
// That constructor has no `throws` clause.
throw newLinkageError(e);
}
}
private static MethodHandle crc32cConstructor() {
try {
Class<?> clazz = Class.forName("java.util.zip.CRC32C");
/*
* We can't cast to CRC32C at the call site because we support building with Java 8
* (https://github.com/google/guava/issues/6549). So we have to use asType() to change from
* CRC32C to Checksum. This may carry some performance cost
* (https://stackoverflow.com/a/22321671/28465), but I'd have to benchmark more carefully to
* even detect it.
*/
return MethodHandles.lookup()
.findConstructor(clazz, methodType(void.class))
.asType(methodType(Checksum.class));
} catch (ClassNotFoundException e) {
// We check that the class is available before calling this method.
throw new AssertionError(e);
} catch (IllegalAccessException e) {
// That API is public.
throw newLinkageError(e);
} catch (NoSuchMethodException e) {
// That constructor exists.
throw newLinkageError(e);
}
}
private static LinkageError newLinkageError(Throwable cause) {
return new LinkageError(cause.toString(), cause);
}
}
/**
* Returns a hash function implementing FarmHash's Fingerprint64, an open-source algorithm.
*
* <p>This is designed for generating persistent fingerprints of strings. It isn't
* cryptographically secure, but it produces a high-quality hash with fewer collisions than some
* alternatives we've used in the past.
*
* <p>FarmHash fingerprints are encoded by {@link HashCode#asBytes} in little-endian order. This
* means {@link HashCode#asLong} is guaranteed to return the same value that
* farmhash::Fingerprint64() would for the same input (when compared using {@link
* com.google.common.primitives.UnsignedLongs}'s encoding of 64-bit unsigned numbers).
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true
* <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 20.0
*/
public static HashFunction farmHashFingerprint64() {
return FarmHashFingerprint64.FARMHASH_FINGERPRINT_64;
}
/**
* Returns a hash function implementing the Fingerprint2011 hashing function (64 hash bits).
*
* <p>This is designed for generating persistent fingerprints of strings. It isn't
* cryptographically secure, but it produces a high-quality hash with few collisions. Fingerprints
* generated using this are byte-wise identical to those created using the C++ version, but note
* that this uses unsigned integers (see {@link com.google.common.primitives.UnsignedInts}).
* Comparisons between the two should take this into account.
*
* <p>Fingerprint2011() is a form of Murmur2 on strings up to 32 bytes and a form of CityHash for
* longer strings. It could have been one or the other throughout. The main advantage of the
* combination is that CityHash has a bunch of special cases for short strings that don't need to
* be replicated here. The result will never be 0 or 1.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true
* <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 31.1
*/
public static HashFunction fingerprint2011() {
return Fingerprint2011.FINGERPRINT_2011;
}
/**
* Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform manner
* that minimizes the need for remapping as {@code buckets} grows. That is, {@code
* consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>This method is suitable for the common use case of dividing work among buckets that meet the
* following conditions:
*
* <ul>
* <li>You want to assign the same fraction of inputs to each bucket.
* <li>When you reduce the number of buckets, you can accept that the most recently added
* buckets will be removed first. More concretely, if you are dividing traffic among tasks,
* you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and
* {@code consistentHash} will handle it. If, however, you are dividing traffic among
* servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to
* take each of the servers offline, {@code consistentHash} will be a poor fit: It provides
* no way for you to specify which of the three buckets is disappearing. Thus, if your
* buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will
* assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo}
* traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic.
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on
* consistent hashing</a> for more information.
*/
public static int consistentHash(HashCode hashCode, int buckets) {
return consistentHash(hashCode.padToLong(), buckets);
}
/**
* Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform manner that
* minimizes the need for remapping as {@code buckets} grows. That is, {@code consistentHash(h,
* n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>This method is suitable for the common use case of dividing work among buckets that meet the
* following conditions:
*
* <ul>
* <li>You want to assign the same fraction of inputs to each bucket.
* <li>When you reduce the number of buckets, you can accept that the most recently added
* buckets will be removed first. More concretely, if you are dividing traffic among tasks,
* you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and
* {@code consistentHash} will handle it. If, however, you are dividing traffic among
* servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to
* take each of the servers offline, {@code consistentHash} will be a poor fit: It provides
* no way for you to specify which of the three buckets is disappearing. Thus, if your
* buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will
* assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo}
* traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic.
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on
* consistent hashing</a> for more information.
*/
public static int consistentHash(long input, int buckets) {
checkArgument(buckets > 0, "buckets must be positive: %s", buckets);
LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input);
int candidate = 0;
int next;
// Jump from bucket to bucket until we go out of range
while (true) {
next = (int) ((candidate + 1) / generator.nextDouble());
if (next >= 0 && next < buckets) {
candidate = next;
} else {
return candidate;
}
}
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes, that combines
* the information of these hash codes in an ordered fashion. That is, whenever two equal hash
* codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
* was computed from the <i>same</i> input hash codes in the <i>same</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
* have the same bit length
*/
public static HashCode combineOrdered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
int bits = iterator.next().bits();
byte[] resultBytes = new byte[bits / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(
nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]);
}
}
return HashCode.fromBytesNoCopy(resultBytes);
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes, that combines
* the information of these hash codes in an unordered fashion. That is, whenever two equal hash
* codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
* was computed from the <i>same</i> input hash codes in <i>some</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
* have the same bit length
*/
public static HashCode combineUnordered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
byte[] resultBytes = new byte[iterator.next().bits() / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(
nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] += nextBytes[i];
}
}
return HashCode.fromBytesNoCopy(resultBytes);
}
/** Checks that the passed argument is positive, and ceils it to a multiple of 32. */
static int checkPositiveAndMakeMultipleOf32(int bits) {
checkArgument(bits > 0, "Number of bits must be positive");
return (bits + 31) & ~31;
}
/**
* Returns a hash function which computes its hash code by concatenating the hash codes of the
* underlying hash functions together. This can be useful if you need to generate hash codes of a
* specific length.
*
* <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
* functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
*
* @since 19.0
*/
public static HashFunction concatenating(
HashFunction first, HashFunction second, HashFunction... rest) {
// We can't use Lists.asList() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<>();
list.add(first);
list.add(second);
Collections.addAll(list, rest);
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
/**
* Returns a hash function which computes its hash code by concatenating the hash codes of the
* underlying hash functions together. This can be useful if you need to generate hash codes of a
* specific length.
*
* <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
* functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
*
* @since 19.0
*/
public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) {
checkNotNull(hashFunctions);
// We can't use Iterables.toArray() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<>();
for (HashFunction hashFunction : hashFunctions) {
list.add(hashFunction);
}
checkArgument(!list.isEmpty(), "number of hash functions (%s) must be > 0", list.size());
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
private static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction {
private ConcatenatedHashFunction(HashFunction... functions) {
super(functions);
for (HashFunction function : functions) {
checkArgument(
function.bits() % 8 == 0,
"the number of bits (%s) in hashFunction (%s) must be divisible by 8",
function.bits(),
function);
}
}
@Override
HashCode makeHash(Hasher[] hashers) {
byte[] bytes = new byte[bits() / 8];
int i = 0;
for (Hasher hasher : hashers) {
HashCode newHash = hasher.hash();
i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8);
}
return HashCode.fromBytesNoCopy(bytes);
}
@Override
public int bits() {
int bitSum = 0;
for (HashFunction function : functions) {
bitSum += function.bits();
}
return bitSum;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof ConcatenatedHashFunction) {
ConcatenatedHashFunction other = (ConcatenatedHashFunction) object;
return Arrays.equals(functions, other.functions);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(functions);
}
}
/**
* Linear CongruentialGenerator to use for consistent hashing. See
* http://en.wikipedia.org/wiki/Linear_congruential_generator
*/
private static final class LinearCongruentialGenerator {
private long state;
public LinearCongruentialGenerator(long seed) {
this.state = seed;
}
public double nextDouble() {
state = 2862933555777941757L * state + 1;
return ((double) ((int) (state >>> 33) + 1)) / 0x1.0p31;
}
}
private Hashing() {}
}