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;
019
020import com.google.common.annotations.Beta;
021import com.google.common.annotations.VisibleForTesting;
022import com.google.common.base.Objects;
023import com.google.common.base.Predicate;
024import com.google.common.hash.BloomFilterStrategies.LockFreeBitArray;
025import com.google.common.math.DoubleMath;
026import com.google.common.primitives.SignedBytes;
027import com.google.common.primitives.UnsignedBytes;
028import com.google.errorprone.annotations.CanIgnoreReturnValue;
029import java.io.DataInputStream;
030import java.io.DataOutputStream;
031import java.io.IOException;
032import java.io.InputStream;
033import java.io.OutputStream;
034import java.io.Serializable;
035import java.math.RoundingMode;
036import org.checkerframework.checker.nullness.compatqual.NullableDecl;
037
038/**
039 * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test
040 * with one-sided error: if it claims that an element is contained in it, this might be in error,
041 * but if it claims that an element is <i>not</i> contained in it, then this is definitely true.
042 *
043 * <p>If you are unfamiliar with Bloom filters, this nice <a
044 * href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand how
045 * they work.
046 *
047 * <p>The false positive probability ({@code FPP}) of a Bloom filter is defined as the probability
048 * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that
049 * has not actually been put in the {@code BloomFilter}.
050 *
051 * <p>Bloom filters are serializable. They also support a more compact serial representation via the
052 * {@link #writeTo} and {@link #readFrom} methods. Both serialized forms will continue to be
053 * supported by future versions of this library. However, serial forms generated by newer versions
054 * of the code may not be readable by older versions of the code (e.g., a serialized Bloom filter
055 * generated today may <i>not</i> be readable by a binary that was compiled 6 months ago).
056 *
057 * <p>As of Guava 23.0, this class is thread-safe and lock-free. It internally uses atomics and
058 * compare-and-swap to ensure correctness when multiple threads are used to access it.
059 *
060 * @param <T> the type of instances that the {@code BloomFilter} accepts
061 * @author Dimitris Andreou
062 * @author Kevin Bourrillion
063 * @since 11.0 (thread-safe since 23.0)
064 */
065@Beta
066public final class BloomFilter<T> implements Predicate<T>, Serializable {
067  /**
068   * A strategy to translate T instances, to {@code numHashFunctions} bit indexes.
069   *
070   * <p>Implementations should be collections of pure functions (i.e. stateless).
071   */
072  interface Strategy extends java.io.Serializable {
073
074    /**
075     * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element.
076     *
077     * <p>Returns whether any bits changed as a result of this operation.
078     */
079    <T> boolean put(
080        T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits);
081
082    /**
083     * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element;
084     * returns {@code true} if and only if all selected bits are set.
085     */
086    <T> boolean mightContain(
087        T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits);
088
089    /**
090     * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. Only
091     * values in the [-128, 127] range are valid for the compact serial form. Non-negative values
092     * are reserved for enums defined in BloomFilterStrategies; negative values are reserved for any
093     * custom, stateful strategy we may define (e.g. any kind of strategy that would depend on user
094     * input).
095     */
096    int ordinal();
097  }
098
099  /** The bit set of the BloomFilter (not necessarily power of 2!) */
100  private final LockFreeBitArray bits;
101
102  /** Number of hashes per element */
103  private final int numHashFunctions;
104
105  /** The funnel to translate Ts to bytes */
106  private final Funnel<? super T> funnel;
107
108  /** The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */
109  private final Strategy strategy;
110
111  /** Creates a BloomFilter. */
112  private BloomFilter(
113      LockFreeBitArray bits, int numHashFunctions, Funnel<? super T> funnel, Strategy strategy) {
114    checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions);
115    checkArgument(
116        numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions);
117    this.bits = checkNotNull(bits);
118    this.numHashFunctions = numHashFunctions;
119    this.funnel = checkNotNull(funnel);
120    this.strategy = checkNotNull(strategy);
121  }
122
123  /**
124   * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to
125   * this instance but shares no mutable state.
126   *
127   * @since 12.0
128   */
129  public BloomFilter<T> copy() {
130    return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy);
131  }
132
133  /**
134   * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, {@code
135   * false} if this is <i>definitely</i> not the case.
136   */
137  public boolean mightContain(T object) {
138    return strategy.mightContain(object, funnel, numHashFunctions, bits);
139  }
140
141  /**
142   * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain}
143   *     instead.
144   */
145  @Deprecated
146  @Override
147  public boolean apply(T input) {
148    return mightContain(input);
149  }
150
151  /**
152   * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of {@link
153   * #mightContain(Object)} with the same element will always return {@code true}.
154   *
155   * @return true if the Bloom filter's bits changed as a result of this operation. If the bits
156   *     changed, this is <i>definitely</i> the first time {@code object} has been added to the
157   *     filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} has
158   *     been added to the filter. Note that {@code put(t)} always returns the <i>opposite</i>
159   *     result to what {@code mightContain(t)} would have returned at the time it is called.
160   * @since 12.0 (present in 11.0 with {@code void} return type})
161   */
162  @CanIgnoreReturnValue
163  public boolean put(T object) {
164    return strategy.put(object, funnel, numHashFunctions, bits);
165  }
166
167  /**
168   * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return {@code
169   * true} for an object that has not actually been put in the {@code BloomFilter}.
170   *
171   * <p>Ideally, this number should be close to the {@code fpp} parameter passed in {@linkplain
172   * #create(Funnel, int, double)}, or smaller. If it is significantly higher, it is usually the
173   * case that too many elements (more than expected) have been put in the {@code BloomFilter},
174   * degenerating it.
175   *
176   * @since 14.0 (since 11.0 as expectedFalsePositiveProbability())
177   */
178  public double expectedFpp() {
179    return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions);
180  }
181
182  /**
183   * Returns an estimate for the total number of distinct elements that have been added to this
184   * Bloom filter. This approximation is reasonably accurate if it does not exceed the value of
185   * {@code expectedInsertions} that was used when constructing the filter.
186   *
187   * @since 22.0
188   */
189  public long approximateElementCount() {
190    long bitSize = bits.bitSize();
191    long bitCount = bits.bitCount();
192
193    /**
194     * Each insertion is expected to reduce the # of clear bits by a factor of
195     * `numHashFunctions/bitSize`. So, after n insertions, expected bitCount is `bitSize * (1 - (1 -
196     * numHashFunctions/bitSize)^n)`. Solving that for n, and approximating `ln x` as `x - 1` when x
197     * is close to 1 (why?), gives the following formula.
198     */
199    double fractionOfBitsSet = (double) bitCount / bitSize;
200    return DoubleMath.roundToLong(
201        -Math.log1p(-fractionOfBitsSet) * bitSize / numHashFunctions, RoundingMode.HALF_UP);
202  }
203
204  /** Returns the number of bits in the underlying bit array. */
205  @VisibleForTesting
206  long bitSize() {
207    return bits.bitSize();
208  }
209
210  /**
211   * Determines whether a given Bloom filter is compatible with this Bloom filter. For two Bloom
212   * filters to be compatible, they must:
213   *
214   * <ul>
215   *   <li>not be the same instance
216   *   <li>have the same number of hash functions
217   *   <li>have the same bit size
218   *   <li>have the same strategy
219   *   <li>have equal funnels
220   * </ul>
221   *
222   * @param that The Bloom filter to check for compatibility.
223   * @since 15.0
224   */
225  public boolean isCompatible(BloomFilter<T> that) {
226    checkNotNull(that);
227    return this != that
228        && this.numHashFunctions == that.numHashFunctions
229        && this.bitSize() == that.bitSize()
230        && this.strategy.equals(that.strategy)
231        && this.funnel.equals(that.funnel);
232  }
233
234  /**
235   * Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the
236   * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom
237   * filters are appropriately sized to avoid saturating them.
238   *
239   * @param that The Bloom filter to combine this Bloom filter with. It is not mutated.
240   * @throws IllegalArgumentException if {@code isCompatible(that) == false}
241   * @since 15.0
242   */
243  public void putAll(BloomFilter<T> that) {
244    checkNotNull(that);
245    checkArgument(this != that, "Cannot combine a BloomFilter with itself.");
246    checkArgument(
247        this.numHashFunctions == that.numHashFunctions,
248        "BloomFilters must have the same number of hash functions (%s != %s)",
249        this.numHashFunctions,
250        that.numHashFunctions);
251    checkArgument(
252        this.bitSize() == that.bitSize(),
253        "BloomFilters must have the same size underlying bit arrays (%s != %s)",
254        this.bitSize(),
255        that.bitSize());
256    checkArgument(
257        this.strategy.equals(that.strategy),
258        "BloomFilters must have equal strategies (%s != %s)",
259        this.strategy,
260        that.strategy);
261    checkArgument(
262        this.funnel.equals(that.funnel),
263        "BloomFilters must have equal funnels (%s != %s)",
264        this.funnel,
265        that.funnel);
266    this.bits.putAll(that.bits);
267  }
268
269  @Override
270  public boolean equals(@NullableDecl Object object) {
271    if (object == this) {
272      return true;
273    }
274    if (object instanceof BloomFilter) {
275      BloomFilter<?> that = (BloomFilter<?>) object;
276      return this.numHashFunctions == that.numHashFunctions
277          && this.funnel.equals(that.funnel)
278          && this.bits.equals(that.bits)
279          && this.strategy.equals(that.strategy);
280    }
281    return false;
282  }
283
284  @Override
285  public int hashCode() {
286    return Objects.hashCode(numHashFunctions, funnel, strategy, bits);
287  }
288
289  /**
290   * Creates a {@link BloomFilter} with the expected number of insertions and expected false
291   * positive probability.
292   *
293   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
294   * will result in its saturation, and a sharp deterioration of its false positive probability.
295   *
296   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
297   * is.
298   *
299   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
300   * ensuring proper serialization and deserialization, which is important since {@link #equals}
301   * also relies on object identity of funnels.
302   *
303   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
304   * @param expectedInsertions the number of expected insertions to the constructed {@code
305   *     BloomFilter}; must be positive
306   * @param fpp the desired false positive probability (must be positive and less than 1.0)
307   * @return a {@code BloomFilter}
308   */
309  public static <T> BloomFilter<T> create(
310      Funnel<? super T> funnel, int expectedInsertions, double fpp) {
311    return create(funnel, (long) expectedInsertions, fpp);
312  }
313
314  /**
315   * Creates a {@link BloomFilter} with the expected number of insertions and expected false
316   * positive probability.
317   *
318   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
319   * will result in its saturation, and a sharp deterioration of its false positive probability.
320   *
321   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
322   * is.
323   *
324   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
325   * ensuring proper serialization and deserialization, which is important since {@link #equals}
326   * also relies on object identity of funnels.
327   *
328   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
329   * @param expectedInsertions the number of expected insertions to the constructed {@code
330   *     BloomFilter}; must be positive
331   * @param fpp the desired false positive probability (must be positive and less than 1.0)
332   * @return a {@code BloomFilter}
333   * @since 19.0
334   */
335  public static <T> BloomFilter<T> create(
336      Funnel<? super T> funnel, long expectedInsertions, double fpp) {
337    return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64);
338  }
339
340  @VisibleForTesting
341  static <T> BloomFilter<T> create(
342      Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) {
343    checkNotNull(funnel);
344    checkArgument(
345        expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions);
346    checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
347    checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
348    checkNotNull(strategy);
349
350    if (expectedInsertions == 0) {
351      expectedInsertions = 1;
352    }
353    /*
354     * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size
355     * is proportional to -log(p), but there is not much of a point after all, e.g.
356     * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares!
357     */
358    long numBits = optimalNumOfBits(expectedInsertions, fpp);
359    int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
360    try {
361      return new BloomFilter<T>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy);
362    } catch (IllegalArgumentException e) {
363      throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
364    }
365  }
366
367  /**
368   * Creates a {@link BloomFilter} with the expected number of insertions and a default expected
369   * false positive probability of 3%.
370   *
371   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
372   * will result in its saturation, and a sharp deterioration of its false positive probability.
373   *
374   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
375   * is.
376   *
377   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
378   * ensuring proper serialization and deserialization, which is important since {@link #equals}
379   * also relies on object identity of funnels.
380   *
381   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
382   * @param expectedInsertions the number of expected insertions to the constructed {@code
383   *     BloomFilter}; must be positive
384   * @return a {@code BloomFilter}
385   */
386  public static <T> BloomFilter<T> create(Funnel<? super T> funnel, int expectedInsertions) {
387    return create(funnel, (long) expectedInsertions);
388  }
389
390  /**
391   * Creates a {@link BloomFilter} with the expected number of insertions and a default expected
392   * false positive probability of 3%.
393   *
394   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
395   * will result in its saturation, and a sharp deterioration of its false positive probability.
396   *
397   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
398   * is.
399   *
400   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
401   * ensuring proper serialization and deserialization, which is important since {@link #equals}
402   * also relies on object identity of funnels.
403   *
404   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
405   * @param expectedInsertions the number of expected insertions to the constructed {@code
406   *     BloomFilter}; must be positive
407   * @return a {@code BloomFilter}
408   * @since 19.0
409   */
410  public static <T> BloomFilter<T> create(Funnel<? super T> funnel, long expectedInsertions) {
411    return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions
412  }
413
414  // Cheat sheet:
415  //
416  // m: total bits
417  // n: expected insertions
418  // b: m/n, bits per insertion
419  // p: expected false positive probability
420  //
421  // 1) Optimal k = b * ln2
422  // 2) p = (1 - e ^ (-kn/m))^k
423  // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b
424  // 4) For optimal k: m = -nlnp / ((ln2) ^ 2)
425
426  /**
427   * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the
428   * expected insertions and total number of bits in the Bloom filter.
429   *
430   * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula.
431   *
432   * @param n expected insertions (must be positive)
433   * @param m total number of bits in Bloom filter (must be positive)
434   */
435  @VisibleForTesting
436  static int optimalNumOfHashFunctions(long n, long m) {
437    // (m / n) * log(2), but avoid truncation due to division!
438    return Math.max(1, (int) Math.round((double) m / n * Math.log(2)));
439  }
440
441  /**
442   * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified
443   * expected insertions, the required false positive probability.
444   *
445   * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the
446   * formula.
447   *
448   * @param n expected insertions (must be positive)
449   * @param p false positive rate (must be 0 < p < 1)
450   */
451  @VisibleForTesting
452  static long optimalNumOfBits(long n, double p) {
453    if (p == 0) {
454      p = Double.MIN_VALUE;
455    }
456    return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2)));
457  }
458
459  private Object writeReplace() {
460    return new SerialForm<T>(this);
461  }
462
463  private static class SerialForm<T> implements Serializable {
464    final long[] data;
465    final int numHashFunctions;
466    final Funnel<? super T> funnel;
467    final Strategy strategy;
468
469    SerialForm(BloomFilter<T> bf) {
470      this.data = LockFreeBitArray.toPlainArray(bf.bits.data);
471      this.numHashFunctions = bf.numHashFunctions;
472      this.funnel = bf.funnel;
473      this.strategy = bf.strategy;
474    }
475
476    Object readResolve() {
477      return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy);
478    }
479
480    private static final long serialVersionUID = 1;
481  }
482
483  /**
484   * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
485   * serialization). This has been measured to save at least 400 bytes compared to regular
486   * serialization.
487   *
488   * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
489   */
490  public void writeTo(OutputStream out) throws IOException {
491    // Serial form:
492    // 1 signed byte for the strategy
493    // 1 unsigned byte for the number of hash functions
494    // 1 big endian int, the number of longs in our bitset
495    // N big endian longs of our bitset
496    DataOutputStream dout = new DataOutputStream(out);
497    dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
498    dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
499    dout.writeInt(bits.data.length());
500    for (int i = 0; i < bits.data.length(); i++) {
501      dout.writeLong(bits.data.get(i));
502    }
503  }
504
505  /**
506   * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code
507   * BloomFilter}.
508   *
509   * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here.
510   * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate
511   * the original Bloom filter!
512   *
513   * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
514   *     appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method.
515   */
516  public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<? super T> funnel)
517      throws IOException {
518    checkNotNull(in, "InputStream");
519    checkNotNull(funnel, "Funnel");
520    int strategyOrdinal = -1;
521    int numHashFunctions = -1;
522    int dataLength = -1;
523    try {
524      DataInputStream din = new DataInputStream(in);
525      // currently this assumes there is no negative ordinal; will have to be updated if we
526      // add non-stateless strategies (for which we've reserved negative ordinals; see
527      // Strategy.ordinal()).
528      strategyOrdinal = din.readByte();
529      numHashFunctions = UnsignedBytes.toInt(din.readByte());
530      dataLength = din.readInt();
531
532      Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal];
533      long[] data = new long[dataLength];
534      for (int i = 0; i < data.length; i++) {
535        data[i] = din.readLong();
536      }
537      return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy);
538    } catch (RuntimeException e) {
539      String message =
540          "Unable to deserialize BloomFilter from InputStream."
541              + " strategyOrdinal: "
542              + strategyOrdinal
543              + " numHashFunctions: "
544              + numHashFunctions
545              + " dataLength: "
546              + dataLength;
547      throw new IOException(message, e);
548    }
549  }
550}