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    
015    package com.google.common.hash;
016    
017    import static com.google.common.base.Preconditions.checkArgument;
018    import static com.google.common.base.Preconditions.checkNotNull;
019    
020    import com.google.common.annotations.Beta;
021    import com.google.common.annotations.VisibleForTesting;
022    import com.google.common.base.Preconditions;
023    import com.google.common.hash.BloomFilterStrategies.BitArray;
024    
025    import java.io.Serializable;
026    
027    /**
028     * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test
029     * with one-sided error: if it claims that an element is contained in it, this might be in error,
030     * but if it claims that an element is <i>not</i> contained in it, then this is definitely true.
031     *
032     * <p>If you are unfamiliar with Bloom filters, this nice
033     * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand
034     * how they work.
035     *
036     * @param <T> the type of instances that the {@code BloomFilter} accepts
037     * @author Dimitris Andreou
038     * @author Kevin Bourrillion
039     * @since 11.0
040     */
041    @Beta
042    public final class BloomFilter<T> implements Serializable {
043      /*
044       * TODO(user): add this above (when the other serial form is published):
045       * <p>Bloom filters are serializable, but also support a more compact serial
046       * representation via the {} and {} methods. Both serialized forms will continue to
047       * be supported by future versions of this library.
048       */
049    
050      /**
051       * A strategy to translate T instances, to {@code numHashFunctions} bit indexes.
052       *
053       * <p>Implementations should be collections of pure functions (i.e. stateless).
054       */
055      interface Strategy extends java.io.Serializable {
056    
057        /**
058         * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element.
059         *
060         * <p>Returns whether any bits changed as a result of this operation.
061         */
062        <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
063    
064        /**
065         * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element;
066         * returns {@code true} if and only if all selected bits are set.
067         */
068        <T> boolean mightContain(
069            T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
070    
071        /**
072         * Identifier used to encode this strategy, when marshalled as part of a BloomFilter.
073         * Only values in the [-128, 127] range are valid for the compact serial form.
074         * Non-negative values are reserved for enums defined in BloomFilterStrategies;
075         * negative values are reserved for any custom, stateful strategy we may define
076         * (e.g. any kind of strategy that would depend on user input).
077         */
078        int ordinal();
079      }
080    
081      /** The bit set of the BloomFilter (not necessarily power of 2!)*/
082      private final BitArray bits;
083    
084      /** Number of hashes per element */
085      private final int numHashFunctions;
086    
087      /** The funnel to translate Ts to bytes */
088      private final Funnel<T> funnel;
089    
090      /**
091       * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes.
092       */
093      private final Strategy strategy;
094    
095      /**
096       * Creates a BloomFilter.
097       */
098      private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel,
099          Strategy strategy) {
100        Preconditions.checkArgument(numHashFunctions > 0, "numHashFunctions zero or negative");
101        this.bits = checkNotNull(bits);
102        this.numHashFunctions = numHashFunctions;
103        this.funnel = checkNotNull(funnel);
104        this.strategy = strategy;
105    
106        /*
107         * This only exists to forbid BFs that cannot use the compact persistent representation.
108         * If it ever throws, at a user who was not intending to use that representation, we should
109         * reconsider
110         */
111        if (numHashFunctions > 255) {
112          throw new AssertionError("Currently we don't allow BloomFilters that would use more than" +
113              "255 hash functions, please contact the guava team");
114        }
115      }
116    
117      /**
118       * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to
119       * this instance but shares no mutable state.
120       *
121       * @since 12.0
122       */
123      public BloomFilter<T> copy() {
124        return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy);
125      }
126    
127      /**
128       * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter,
129       * {@code false} if this is <i>definitely</i> not the case.
130       */
131      public boolean mightContain(T object) {
132        return strategy.mightContain(object, funnel, numHashFunctions, bits);
133      }
134    
135      /**
136       * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of
137       * {@link #mightContain(Object)} with the same element will always return {@code true}.
138       *
139       * @return true if the bloom filter's bits changed as a result of this operation. If the bits
140       *         changed, this is <i>definitely</i> the first time {@code object} has been added to the
141       *         filter. If the bits haven't changed, this <i>might</i> be the first time {@code object}
142       *         has been added to the filter. Note that {@code put(t)} always returns the
143       *         <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time
144       *         it is called."
145       * @since 12.0 (present in 11.0 with {@code void} return type})
146       */
147      public boolean put(T object) {
148        return strategy.put(object, funnel, numHashFunctions, bits);
149      }
150    
151      /**
152       * {@inheritDoc}
153       *
154       * <p>This implementation uses reference equality to compare funnels.
155       */
156      @Override public boolean equals(Object o) {
157        if (o instanceof BloomFilter) {
158          BloomFilter<?> that = (BloomFilter<?>) o;
159          return this.numHashFunctions == that.numHashFunctions
160              && this.bits.equals(that.bits)
161              && this.funnel == that.funnel
162              && this.strategy == that.strategy;
163        }
164        return false;
165      }
166    
167      @Override public int hashCode() {
168        return bits.hashCode();
169      }
170    
171      @VisibleForTesting int getHashCount() {
172        return numHashFunctions;
173      }
174    
175      @VisibleForTesting double computeExpectedFalsePositiveRate(int insertions) {
176        return Math.pow(
177            1 - Math.exp(-numHashFunctions * ((double) insertions / (bits.size()))),
178            numHashFunctions);
179      }
180    
181      /**
182       * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number
183       * of insertions and expected false positive probability.
184       *
185       * <p>Note that overflowing a {@code BloomFilter} with significantly more elements
186       * than specified, will result in its saturation, and a sharp deterioration of its
187       * false positive probability.
188       *
189       * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
190       * {@code Funnel<T>} is.
191       *
192       * <p>It is recommended the funnel is implemented as a Java enum. This has the benefit of ensuring
193       * proper serialization and deserialization, which is important since {@link #equals} also relies
194       * on object identity of funnels.
195       *
196       * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
197       * @param expectedInsertions the number of expected insertions to the constructed
198       *        {@code BloomFilter<T>}; must be positive
199       * @param falsePositiveProbability the desired false positive probability (must be positive and
200       *        less than 1.0)
201       * @return a {@code BloomFilter}
202       */
203      public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */,
204          double falsePositiveProbability) {
205        checkNotNull(funnel);
206        checkArgument(expectedInsertions > 0, "Expected insertions must be positive");
207        checkArgument(falsePositiveProbability > 0.0 & falsePositiveProbability < 1.0,
208            "False positive probability in (0.0, 1.0)");
209        /*
210         * andreou: I wanted to put a warning in the javadoc about tiny fpp values,
211         * since the resulting size is proportional to -log(p), but there is not
212         * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680
213         * which is less that 10kb. Who cares!
214         */
215        int numBits = optimalNumOfBits(expectedInsertions, falsePositiveProbability);
216        int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
217        return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel,
218            BloomFilterStrategies.MURMUR128_MITZ_32);
219      }
220    
221      /**
222       * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number
223       * of insertions, and a default expected false positive probability of 3%.
224       *
225       * <p>Note that overflowing a {@code BloomFilter} with significantly more elements
226       * than specified, will result in its saturation, and a sharp deterioration of its
227       * false positive probability.
228       *
229       * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
230       * {@code Funnel<T>} is.
231       *
232       * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
233       * @param expectedInsertions the number of expected insertions to the constructed
234       *        {@code BloomFilter<T>}; must be positive
235       * @return a {@code BloomFilter}
236       */
237      public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) {
238        return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions
239      }
240    
241      /*
242       * Cheat sheet:
243       *
244       * m: total bits
245       * n: expected insertions
246       * b: m/n, bits per insertion
247    
248       * p: expected false positive probability
249       *
250       * 1) Optimal k = b * ln2
251       * 2) p = (1 - e ^ (-kn/m))^k
252       * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b
253       * 4) For optimal k: m = -nlnp / ((ln2) ^ 2)
254       */
255    
256      private static final double LN2 = Math.log(2);
257      private static final double LN2_SQUARED = LN2 * LN2;
258    
259      /**
260       * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the
261       * expected insertions and total number of bits in the Bloom filter.
262       *
263       * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula.
264       *
265       * @param n expected insertions (must be positive)
266       * @param m total number of bits in Bloom filter (must be positive)
267       */
268      @VisibleForTesting static int optimalNumOfHashFunctions(int n, int m) {
269        return Math.max(1, (int) Math.round(m / n * LN2));
270      }
271    
272      /**
273       * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified
274       * expected insertions, the required false positive probability.
275       *
276       * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula.
277       *
278       * @param n expected insertions (must be positive)
279       * @param p false positive rate (must be 0 < p < 1)
280       */
281      @VisibleForTesting static int optimalNumOfBits(int n, double p) {
282        return (int) (-n * Math.log(p) / LN2_SQUARED);
283      }
284    
285      private Object writeReplace() {
286        return new SerialForm<T>(this);
287      }
288    
289      private static class SerialForm<T> implements Serializable {
290        final long[] data;
291        final int numHashFunctions;
292        final Funnel<T> funnel;
293        final Strategy strategy;
294    
295        SerialForm(BloomFilter<T> bf) {
296          this.data = bf.bits.data;
297          this.numHashFunctions = bf.numHashFunctions;
298          this.funnel = bf.funnel;
299          this.strategy = bf.strategy;
300        }
301        Object readResolve() {
302          return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
303        }
304        private static final long serialVersionUID = 1;
305      }
306    }