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