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