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