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