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 com.google.errorprone.annotations.InlineMe;
032import java.io.DataInputStream;
033import java.io.DataOutputStream;
034import java.io.IOException;
035import java.io.InputStream;
036import java.io.InvalidObjectException;
037import java.io.ObjectInputStream;
038import java.io.OutputStream;
039import java.io.Serializable;
040import java.math.RoundingMode;
041import java.util.stream.Collector;
042import org.jspecify.annotations.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
072public final class BloomFilter<T extends @Nullable Object> implements Predicate<T>, Serializable {
073  /**
074   * A strategy to translate T instances, to {@code numHashFunctions} bit indexes.
075   *
076   * <p>Implementations should be collections of pure functions (i.e. stateless).
077   */
078  interface Strategy extends java.io.Serializable {
079
080    /**
081     * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element.
082     *
083     * <p>Returns whether any bits changed as a result of this operation.
084     */
085    <T extends @Nullable Object> boolean put(
086        @ParametricNullness T object,
087        Funnel<? super T> funnel,
088        int numHashFunctions,
089        LockFreeBitArray bits);
090
091    /**
092     * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element;
093     * returns {@code true} if and only if all selected bits are set.
094     */
095    <T extends @Nullable Object> boolean mightContain(
096        @ParametricNullness T object,
097        Funnel<? super T> funnel,
098        int numHashFunctions,
099        LockFreeBitArray bits);
100
101    /**
102     * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. Only
103     * values in the [-128, 127] range are valid for the compact serial form. Non-negative values
104     * are reserved for enums defined in BloomFilterStrategies; negative values are reserved for any
105     * custom, stateful strategy we may define (e.g. any kind of strategy that would depend on user
106     * input).
107     */
108    int ordinal();
109  }
110
111  /** The bit set of the BloomFilter (not necessarily power of 2!) */
112  private final LockFreeBitArray bits;
113
114  /** Number of hashes per element */
115  private final int numHashFunctions;
116
117  /** The funnel to translate Ts to bytes */
118  private final Funnel<? super T> funnel;
119
120  /** The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */
121  private final Strategy strategy;
122
123  /** Natural logarithm of 2, used to optimize calculations in Bloom filter sizing. */
124  private static final double LOG_TWO = Math.log(2);
125
126  /** Square of the natural logarithm of 2, reused to optimize the bit size calculation. */
127  private static final double SQUARED_LOG_TWO = LOG_TWO * LOG_TWO;
128
129  /** Creates a BloomFilter. */
130  private BloomFilter(
131      LockFreeBitArray bits, int numHashFunctions, Funnel<? super T> funnel, Strategy strategy) {
132    checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions);
133    checkArgument(
134        numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions);
135    this.bits = checkNotNull(bits);
136    this.numHashFunctions = numHashFunctions;
137    this.funnel = checkNotNull(funnel);
138    this.strategy = checkNotNull(strategy);
139  }
140
141  /**
142   * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to
143   * this instance but shares no mutable state.
144   *
145   * @since 12.0
146   */
147  public BloomFilter<T> copy() {
148    return new BloomFilter<>(bits.copy(), numHashFunctions, funnel, strategy);
149  }
150
151  /**
152   * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, {@code
153   * false} if this is <i>definitely</i> not the case.
154   */
155  public boolean mightContain(@ParametricNullness T object) {
156    return strategy.mightContain(object, funnel, numHashFunctions, bits);
157  }
158
159  /**
160   * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain}
161   *     instead.
162   */
163  @InlineMe(replacement = "this.mightContain(input)")
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(@Nullable 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 33.4.0 (but since 23.0 in the JRE flavor)
328   */
329  @SuppressWarnings("Java7ApiChecker")
330  @IgnoreJRERequirement // Users will use this only if they're already using streams.
331  public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter(
332      Funnel<? super T> funnel, long expectedInsertions) {
333    return toBloomFilter(funnel, expectedInsertions, 0.03);
334  }
335
336  /**
337   * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link
338   * BloomFilter} with the specified expected false positive probability.
339   *
340   * <p>Note that if the {@code Collector} receives significantly more elements than specified, the
341   * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive
342   * probability.
343   *
344   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
345   * is.
346   *
347   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
348   * ensuring proper serialization and deserialization, which is important since {@link #equals}
349   * also relies on object identity of funnels.
350   *
351   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
352   * @param expectedInsertions the number of expected insertions to the constructed {@code
353   *     BloomFilter}; must be positive
354   * @param fpp the desired false positive probability (must be positive and less than 1.0)
355   * @return a {@code Collector} generating a {@code BloomFilter} of the received elements
356   * @since 33.4.0 (but since 23.0 in the JRE flavor)
357   */
358  @SuppressWarnings("Java7ApiChecker")
359  @IgnoreJRERequirement // Users will use this only if they're already using streams.
360  public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter(
361      Funnel<? super T> funnel, long expectedInsertions, double fpp) {
362    checkNotNull(funnel);
363    checkArgument(
364        expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions);
365    checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
366    checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
367    return Collector.of(
368        () -> BloomFilter.create(funnel, expectedInsertions, fpp),
369        BloomFilter::put,
370        (bf1, bf2) -> {
371          bf1.putAll(bf2);
372          return bf1;
373        },
374        Collector.Characteristics.UNORDERED,
375        Collector.Characteristics.CONCURRENT);
376  }
377
378  /**
379   * Creates a {@link BloomFilter} with the expected number of insertions and expected false
380   * positive probability.
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   * @param fpp the desired false positive probability (must be positive and less than 1.0)
396   * @return a {@code BloomFilter}
397   */
398  public static <T extends @Nullable Object> BloomFilter<T> create(
399      Funnel<? super T> funnel, int expectedInsertions, double fpp) {
400    return create(funnel, (long) expectedInsertions, fpp);
401  }
402
403  /**
404   * Creates a {@link BloomFilter} with the expected number of insertions and expected false
405   * positive probability.
406   *
407   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
408   * will result in its saturation, and a sharp deterioration of its false positive probability.
409   *
410   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
411   * is.
412   *
413   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
414   * ensuring proper serialization and deserialization, which is important since {@link #equals}
415   * also relies on object identity of funnels.
416   *
417   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
418   * @param expectedInsertions the number of expected insertions to the constructed {@code
419   *     BloomFilter}; must be positive
420   * @param fpp the desired false positive probability (must be positive and less than 1.0)
421   * @return a {@code BloomFilter}
422   * @since 19.0
423   */
424  public static <T extends @Nullable Object> BloomFilter<T> create(
425      Funnel<? super T> funnel, long expectedInsertions, double fpp) {
426    return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64);
427  }
428
429  @VisibleForTesting
430  static <T extends @Nullable Object> BloomFilter<T> create(
431      Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) {
432    checkNotNull(funnel);
433    checkArgument(
434        expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions);
435    checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
436    checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
437    checkNotNull(strategy);
438
439    if (expectedInsertions == 0) {
440      expectedInsertions = 1;
441    }
442    /*
443     * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size
444     * is proportional to -log(p), but there is not much of a point after all, e.g.
445     * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares!
446     */
447    long numBits = optimalNumOfBits(expectedInsertions, fpp);
448    int numHashFunctions = optimalNumOfHashFunctions(fpp);
449    try {
450      return new BloomFilter<>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy);
451    } catch (IllegalArgumentException e) {
452      throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
453    }
454  }
455
456  /**
457   * Creates a {@link BloomFilter} with the expected number of insertions and a default expected
458   * false positive probability of 3%.
459   *
460   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
461   * will result in its saturation, and a sharp deterioration of its false positive probability.
462   *
463   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
464   * is.
465   *
466   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
467   * ensuring proper serialization and deserialization, which is important since {@link #equals}
468   * also relies on object identity of funnels.
469   *
470   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
471   * @param expectedInsertions the number of expected insertions to the constructed {@code
472   *     BloomFilter}; must be positive
473   * @return a {@code BloomFilter}
474   */
475  public static <T extends @Nullable Object> BloomFilter<T> create(
476      Funnel<? super T> funnel, int expectedInsertions) {
477    return create(funnel, (long) expectedInsertions);
478  }
479
480  /**
481   * Creates a {@link BloomFilter} with the expected number of insertions and a default expected
482   * false positive probability of 3%.
483   *
484   * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified,
485   * will result in its saturation, and a sharp deterioration of its false positive probability.
486   *
487   * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>}
488   * is.
489   *
490   * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of
491   * ensuring proper serialization and deserialization, which is important since {@link #equals}
492   * also relies on object identity of funnels.
493   *
494   * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use
495   * @param expectedInsertions the number of expected insertions to the constructed {@code
496   *     BloomFilter}; must be positive
497   * @return a {@code BloomFilter}
498   * @since 19.0
499   */
500  public static <T extends @Nullable Object> BloomFilter<T> create(
501      Funnel<? super T> funnel, long expectedInsertions) {
502    return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions
503  }
504
505  // Cheat sheet:
506  //
507  // m: total bits
508  // n: expected insertions
509  // b: m/n, bits per insertion
510  // p: expected false positive probability
511  //
512  // 1) Optimal k = b * ln2
513  // 2) p = (1 - e ^ (-kn/m))^k
514  // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b
515  // 4) For optimal k: m = -nlnp / ((ln2) ^ 2)
516
517  /**
518   * Computes the optimal number of hash functions (k) for a given false positive probability (p).
519   *
520   * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula.
521   *
522   * @param p desired false positive probability (must be between 0 and 1, exclusive)
523   */
524  @VisibleForTesting
525  static int optimalNumOfHashFunctions(double p) {
526    // -log(p) / log(2), ensuring the result is rounded to avoid truncation.
527    return max(1, (int) Math.round(-Math.log(p) / LOG_TWO));
528  }
529
530  /**
531   * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified
532   * expected insertions, the required false positive probability.
533   *
534   * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the
535   * formula.
536   *
537   * @param n expected insertions (must be positive)
538   * @param p false positive rate (must be 0 < p < 1)
539   */
540  @VisibleForTesting
541  static long optimalNumOfBits(long n, double p) {
542    if (p == 0) {
543      p = Double.MIN_VALUE;
544    }
545    return (long) (-n * Math.log(p) / SQUARED_LOG_TWO);
546  }
547
548  private Object writeReplace() {
549    return new SerialForm<T>(this);
550  }
551
552  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
553    throw new InvalidObjectException("Use SerializedForm");
554  }
555
556  private static class SerialForm<T extends @Nullable Object> implements Serializable {
557    final long[] data;
558    final int numHashFunctions;
559    final Funnel<? super T> funnel;
560    final Strategy strategy;
561
562    SerialForm(BloomFilter<T> bf) {
563      this.data = LockFreeBitArray.toPlainArray(bf.bits.data);
564      this.numHashFunctions = bf.numHashFunctions;
565      this.funnel = bf.funnel;
566      this.strategy = bf.strategy;
567    }
568
569    Object readResolve() {
570      return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy);
571    }
572
573    private static final long serialVersionUID = 1;
574  }
575
576  /**
577   * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
578   * serialization). This has been measured to save at least 400 bytes compared to regular
579   * serialization.
580   *
581   * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
582   */
583  public void writeTo(OutputStream out) throws IOException {
584    // Serial form:
585    // 1 signed byte for the strategy
586    // 1 unsigned byte for the number of hash functions
587    // 1 big endian int, the number of longs in our bitset
588    // N big endian longs of our bitset
589    DataOutputStream dout = new DataOutputStream(out);
590    dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
591    dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
592    dout.writeInt(bits.data.length());
593    for (int i = 0; i < bits.data.length(); i++) {
594      dout.writeLong(bits.data.get(i));
595    }
596  }
597
598  /**
599   * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code
600   * BloomFilter}.
601   *
602   * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here.
603   * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate
604   * the original Bloom filter!
605   *
606   * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
607   *     appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method.
608   */
609  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
610  public static <T extends @Nullable Object> BloomFilter<T> readFrom(
611      InputStream in, Funnel<? super T> funnel) throws IOException {
612    checkNotNull(in, "InputStream");
613    checkNotNull(funnel, "Funnel");
614    int strategyOrdinal = -1;
615    int numHashFunctions = -1;
616    int dataLength = -1;
617    try {
618      DataInputStream din = new DataInputStream(in);
619      // currently this assumes there is no negative ordinal; will have to be updated if we
620      // add non-stateless strategies (for which we've reserved negative ordinals; see
621      // Strategy.ordinal()).
622      strategyOrdinal = din.readByte();
623      numHashFunctions = UnsignedBytes.toInt(din.readByte());
624      dataLength = din.readInt();
625
626      Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal];
627
628      LockFreeBitArray dataArray = new LockFreeBitArray(LongMath.checkedMultiply(dataLength, 64L));
629      for (int i = 0; i < dataLength; i++) {
630        dataArray.putData(i, din.readLong());
631      }
632
633      return new BloomFilter<>(dataArray, numHashFunctions, funnel, strategy);
634    } catch (IOException e) {
635      throw e;
636    } catch (Exception e) { // sneaky checked exception
637      String message =
638          "Unable to deserialize BloomFilter from InputStream."
639              + " strategyOrdinal: "
640              + strategyOrdinal
641              + " numHashFunctions: "
642              + numHashFunctions
643              + " dataLength: "
644              + dataLength;
645      throw new IOException(message, e);
646    }
647  }
648
649  private static final long serialVersionUID = 0xdecaf;
650}