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;
025
026import java.io.Serializable;
027
028import javax.annotation.Nullable;
029
030/**
031 * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test
032 * with one-sided error: if it claims that an element is contained in it, this might be in error,
033 * but if it claims that an element is <i>not</i> contained in it, then this is definitely true.
034 *
035 * <p>If you are unfamiliar with Bloom filters, this nice
036 * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand
037 * how they work.
038 *
039 * <p>The false positive probability ({@code FPP}) of a bloom filter is defined as the probability
040 * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that
041 * has not actually been put in the {@code BloomFilter}.
042 *
043 *
044 * @param <T> the type of instances that the {@code BloomFilter} accepts
045 * @author Dimitris Andreou
046 * @author Kevin Bourrillion
047 * @since 11.0
048 */
049@Beta
050public final class BloomFilter<T> implements Predicate<T>, Serializable {
051  /**
052   * A strategy to translate T instances, to {@code numHashFunctions} bit indexes.
053   *
054   * <p>Implementations should be collections of pure functions (i.e. stateless).
055   */
056  interface Strategy extends java.io.Serializable {
057
058    /**
059     * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element.
060     *
061     * <p>Returns whether any bits changed as a result of this operation.
062     */
063    <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
064
065    /**
066     * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element;
067     * returns {@code true} if and only if all selected bits are set.
068     */
069    <T> boolean mightContain(
070        T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
071
072    /**
073     * Identifier used to encode this strategy, when marshalled as part of a BloomFilter.
074     * Only values in the [-128, 127] range are valid for the compact serial form.
075     * Non-negative values are reserved for enums defined in BloomFilterStrategies;
076     * negative values are reserved for any custom, stateful strategy we may define
077     * (e.g. any kind of strategy that would depend on user input).
078     */
079    int ordinal();
080  }
081
082  /** The bit set of the BloomFilter (not necessarily power of 2!)*/
083  private final BitArray bits;
084
085  /** Number of hashes per element */
086  private final int numHashFunctions;
087
088  /** The funnel to translate Ts to bytes */
089  private final Funnel<T> funnel;
090
091  /**
092   * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes.
093   */
094  private final Strategy strategy;
095
096  /**
097   * Creates a BloomFilter.
098   */
099  private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel,
100      Strategy strategy) {
101    checkArgument(numHashFunctions > 0,
102        "numHashFunctions (%s) must be > 0", numHashFunctions);
103    checkArgument(numHashFunctions <= 255,
104        "numHashFunctions (%s) must be <= 255", numHashFunctions);
105    this.bits = checkNotNull(bits);
106    this.numHashFunctions = numHashFunctions;
107    this.funnel = checkNotNull(funnel);
108    this.strategy = checkNotNull(strategy);
109  }
110
111  /**
112   * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to
113   * this instance but shares no mutable state.
114   *
115   * @since 12.0
116   */
117  public BloomFilter<T> copy() {
118    return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy);
119  }
120
121  /**
122   * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter,
123   * {@code false} if this is <i>definitely</i> not the case.
124   */
125  public boolean mightContain(T object) {
126    return strategy.mightContain(object, funnel, numHashFunctions, bits);
127  }
128
129  /**
130   * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain}
131   *     instead.
132   */
133  @Deprecated
134  @Override
135  public boolean apply(T input) {
136    return mightContain(input);
137  }
138
139  /**
140   * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of
141   * {@link #mightContain(Object)} with the same element will always return {@code true}.
142   *
143   * @return true if the bloom filter's bits changed as a result of this operation. If the bits
144   *     changed, this is <i>definitely</i> the first time {@code object} has been added to the
145   *     filter. If the bits haven't changed, this <i>might</i> be the first time {@code object}
146   *     has been added to the filter. Note that {@code put(t)} always returns the
147   *     <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time
148   *     it is called."
149   * @since 12.0 (present in 11.0 with {@code void} return type})
150   */
151  public boolean put(T object) {
152    return strategy.put(object, funnel, numHashFunctions, bits);
153  }
154
155  /**
156   * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return
157   * {@code true} for an object that has not actually been put in the {@code BloomFilter}.
158   *
159   * <p>Ideally, this number should be close to the {@code fpp} parameter
160   * passed in {@linkplain #create(Funnel, int, double)}, or smaller. If it is
161   * significantly higher, it is usually the case that too many elements (more than
162   * expected) have been put in the {@code BloomFilter}, degenerating it.
163   *
164   * @since 14.0 (since 11.0 as expectedFalsePositiveProbability())
165   */
166  public double expectedFpp() {
167    // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last homie!)
168    return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions);
169  }
170
171  /**
172   * Returns the number of bits in the underlying bit array.
173   */
174  @VisibleForTesting long bitSize() {
175    return bits.bitSize();
176  }
177
178  /**
179   * Determines whether a given bloom filter is compatible with this bloom filter. For two
180   * bloom filters to be compatible, they must:
181   *
182   * <ul>
183   * <li>not be the same instance
184   * <li>have the same number of hash functions
185   * <li>have the same bit size
186   * <li>have the same strategy
187   * <li>have equal funnels
188   * <ul>
189   *
190   * @param that The bloom filter to check for compatibility.
191   * @since 15.0
192   */
193  public boolean isCompatible(BloomFilter<T> that) {
194    checkNotNull(that);
195    return (this != that) &&
196        (this.numHashFunctions == that.numHashFunctions) &&
197        (this.bitSize() == that.bitSize()) &&
198        (this.strategy.equals(that.strategy)) &&
199        (this.funnel.equals(that.funnel));
200  }
201
202  /**
203   * Combines this bloom filter with another bloom filter by performing a bitwise OR of the
204   * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the
205   * bloom filters are appropriately sized to avoid saturating them.
206   *
207   * @param that The bloom filter to combine this bloom filter with. It is not mutated.
208   * @throws IllegalArgumentException if {@code isCompatible(that) == false}
209   *
210   * @since 15.0
211   */
212  public void putAll(BloomFilter<T> that) {
213    checkNotNull(that);
214    checkArgument(this != that, "Cannot combine a BloomFilter with itself.");
215    checkArgument(this.numHashFunctions == that.numHashFunctions,
216        "BloomFilters must have the same number of hash functions (%s != %s)",
217        this.numHashFunctions, that.numHashFunctions);
218    checkArgument(this.bitSize() == that.bitSize(),
219        "BloomFilters must have the same size underlying bit arrays (%s != %s)",
220        this.bitSize(), that.bitSize());
221    checkArgument(this.strategy.equals(that.strategy),
222        "BloomFilters must have equal strategies (%s != %s)",
223        this.strategy, that.strategy);
224    checkArgument(this.funnel.equals(that.funnel),
225        "BloomFilters must have equal funnels (%s != %s)",
226        this.funnel, that.funnel);
227    this.bits.putAll(that.bits);
228  }
229
230  @Override
231  public boolean equals(@Nullable Object object) {
232    if (object == this) {
233      return true;
234    }
235    if (object instanceof BloomFilter) {
236      BloomFilter<?> that = (BloomFilter<?>) object;
237      return this.numHashFunctions == that.numHashFunctions
238          && this.funnel.equals(that.funnel)
239          && this.bits.equals(that.bits)
240          && this.strategy.equals(that.strategy);
241    }
242    return false;
243  }
244
245  @Override
246  public int hashCode() {
247    return Objects.hashCode(numHashFunctions, funnel, strategy, bits);
248  }
249
250  /**
251   * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of
252   * insertions and expected false positive probability.
253   *
254   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements
255   * than specified, will result in its saturation, and a sharp deterioration of its
256   * false positive probability.
257   *
258   * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
259   * {@code Funnel<T>} is.
260   *
261   * <p>It is recommended that the funnel be implemented as a Java enum. This has the
262   * benefit of ensuring proper serialization and deserialization, which is important
263   * since {@link #equals} also relies on object identity of funnels.
264   *
265   * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
266   * @param expectedInsertions the number of expected insertions to the constructed
267   *     {@code BloomFilter<T>}; must be positive
268   * @param fpp the desired false positive probability (must be positive and less than 1.0)
269   * @return a {@code BloomFilter}
270   */
271  public static <T> BloomFilter<T> create(
272      Funnel<T> funnel, int expectedInsertions /* n */, double fpp) {
273    checkNotNull(funnel);
274    checkArgument(expectedInsertions >= 0, "Expected insertions (%s) must be >= 0",
275        expectedInsertions);
276    checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
277    checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
278    if (expectedInsertions == 0) {
279      expectedInsertions = 1;
280    }
281    /*
282     * TODO(user): Put a warning in the javadoc about tiny fpp values,
283     * since the resulting size is proportional to -log(p), but there is not
284     * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680
285     * which is less than 10kb. Who cares!
286     */
287    long numBits = optimalNumOfBits(expectedInsertions, fpp);
288    int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
289    try {
290      return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel,
291          BloomFilterStrategies.MURMUR128_MITZ_32);
292    } catch (IllegalArgumentException e) {
293      throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
294    }
295  }
296
297  /**
298   * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of
299   * insertions and a default expected false positive probability of 3%.
300   *
301   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements
302   * than specified, will result in its saturation, and a sharp deterioration of its
303   * false positive probability.
304   *
305   * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
306   * {@code Funnel<T>} is.
307   *
308   * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
309   * @param expectedInsertions the number of expected insertions to the constructed
310   *     {@code BloomFilter<T>}; must be positive
311   * @return a {@code BloomFilter}
312   */
313  public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) {
314    return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions
315  }
316
317  /*
318   * Cheat sheet:
319   *
320   * m: total bits
321   * n: expected insertions
322   * b: m/n, bits per insertion
323   * p: expected false positive probability
324   *
325   * 1) Optimal k = b * ln2
326   * 2) p = (1 - e ^ (-kn/m))^k
327   * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b
328   * 4) For optimal k: m = -nlnp / ((ln2) ^ 2)
329   */
330
331  /**
332   * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the
333   * expected insertions and total number of bits in the Bloom filter.
334   *
335   * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula.
336   *
337   * @param n expected insertions (must be positive)
338   * @param m total number of bits in Bloom filter (must be positive)
339   */
340  @VisibleForTesting
341  static int optimalNumOfHashFunctions(long n, long m) {
342    return Math.max(1, (int) Math.round(m / n * Math.log(2)));
343  }
344
345  /**
346   * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified
347   * expected insertions, the required false positive probability.
348   *
349   * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula.
350   *
351   * @param n expected insertions (must be positive)
352   * @param p false positive rate (must be 0 < p < 1)
353   */
354  @VisibleForTesting
355  static long optimalNumOfBits(long n, double p) {
356    if (p == 0) {
357      p = Double.MIN_VALUE;
358    }
359    return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2)));
360  }
361
362  private Object writeReplace() {
363    return new SerialForm<T>(this);
364  }
365
366  private static class SerialForm<T> implements Serializable {
367    final long[] data;
368    final int numHashFunctions;
369    final Funnel<T> funnel;
370    final Strategy strategy;
371
372    SerialForm(BloomFilter<T> bf) {
373      this.data = bf.bits.data;
374      this.numHashFunctions = bf.numHashFunctions;
375      this.funnel = bf.funnel;
376      this.strategy = bf.strategy;
377    }
378    Object readResolve() {
379      return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
380    }
381    private static final long serialVersionUID = 1;
382  }
383}