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