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 * @deprecated Provided only to satisfy the {@link java.util.function.Predicate} interface; use 172 * {@link #mightContain} instead. 173 * @since 21.0 174 */ 175 @InlineMe(replacement = "this.mightContain(input)") 176 @Deprecated 177 @Override 178 public boolean test(@ParametricNullness T input) { 179 return mightContain(input); 180 } 181 182 /** 183 * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of {@link 184 * #mightContain(Object)} with the same element will always return {@code true}. 185 * 186 * @return true if the Bloom filter's bits changed as a result of this operation. If the bits 187 * changed, this is <i>definitely</i> the first time {@code object} has been added to the 188 * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} has 189 * been added to the filter. Note that {@code put(t)} always returns the <i>opposite</i> 190 * result to what {@code mightContain(t)} would have returned at the time it is called. 191 * @since 12.0 (present in 11.0 with {@code void} return type}) 192 */ 193 @CanIgnoreReturnValue 194 public boolean put(@ParametricNullness T object) { 195 return strategy.put(object, funnel, numHashFunctions, bits); 196 } 197 198 /** 199 * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return {@code 200 * true} for an object that has not actually been put in the {@code BloomFilter}. 201 * 202 * <p>Ideally, this number should be close to the {@code fpp} parameter passed in {@linkplain 203 * #create(Funnel, int, double)}, or smaller. If it is significantly higher, it is usually the 204 * case that too many elements (more than expected) have been put in the {@code BloomFilter}, 205 * degenerating it. 206 * 207 * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) 208 */ 209 public double expectedFpp() { 210 return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); 211 } 212 213 /** 214 * Returns an estimate for the total number of distinct elements that have been added to this 215 * Bloom filter. This approximation is reasonably accurate if it does not exceed the value of 216 * {@code expectedInsertions} that was used when constructing the filter. 217 * 218 * @since 22.0 219 */ 220 public long approximateElementCount() { 221 long bitSize = bits.bitSize(); 222 long bitCount = bits.bitCount(); 223 224 /* 225 * Each insertion is expected to reduce the # of clear bits by a factor of 226 * `numHashFunctions/bitSize`. So, after n insertions, expected bitCount is `bitSize * (1 - (1 - 227 * numHashFunctions/bitSize)^n)`. Solving that for n, and approximating `ln x` as `x - 1` when x 228 * is close to 1 (why?), gives the following formula. 229 */ 230 double fractionOfBitsSet = (double) bitCount / bitSize; 231 return DoubleMath.roundToLong( 232 -Math.log1p(-fractionOfBitsSet) * bitSize / numHashFunctions, RoundingMode.HALF_UP); 233 } 234 235 /** Returns the number of bits in the underlying bit array. */ 236 @VisibleForTesting 237 long bitSize() { 238 return bits.bitSize(); 239 } 240 241 /** 242 * Determines whether a given Bloom filter is compatible with this Bloom filter. For two Bloom 243 * filters to be compatible, they must: 244 * 245 * <ul> 246 * <li>not be the same instance 247 * <li>have the same number of hash functions 248 * <li>have the same bit size 249 * <li>have the same strategy 250 * <li>have equal funnels 251 * </ul> 252 * 253 * @param that The Bloom filter to check for compatibility. 254 * @since 15.0 255 */ 256 public boolean isCompatible(BloomFilter<T> that) { 257 checkNotNull(that); 258 return this != that 259 && this.numHashFunctions == that.numHashFunctions 260 && this.bitSize() == that.bitSize() 261 && this.strategy.equals(that.strategy) 262 && this.funnel.equals(that.funnel); 263 } 264 265 /** 266 * Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the 267 * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom 268 * filters are appropriately sized to avoid saturating them. 269 * 270 * @param that The Bloom filter to combine this Bloom filter with. It is not mutated. 271 * @throws IllegalArgumentException if {@code isCompatible(that) == false} 272 * @since 15.0 273 */ 274 public void putAll(BloomFilter<T> that) { 275 checkNotNull(that); 276 checkArgument(this != that, "Cannot combine a BloomFilter with itself."); 277 checkArgument( 278 this.numHashFunctions == that.numHashFunctions, 279 "BloomFilters must have the same number of hash functions (%s != %s)", 280 this.numHashFunctions, 281 that.numHashFunctions); 282 checkArgument( 283 this.bitSize() == that.bitSize(), 284 "BloomFilters must have the same size underlying bit arrays (%s != %s)", 285 this.bitSize(), 286 that.bitSize()); 287 checkArgument( 288 this.strategy.equals(that.strategy), 289 "BloomFilters must have equal strategies (%s != %s)", 290 this.strategy, 291 that.strategy); 292 checkArgument( 293 this.funnel.equals(that.funnel), 294 "BloomFilters must have equal funnels (%s != %s)", 295 this.funnel, 296 that.funnel); 297 this.bits.putAll(that.bits); 298 } 299 300 @Override 301 public boolean equals(@Nullable Object object) { 302 if (object == this) { 303 return true; 304 } 305 if (object instanceof BloomFilter) { 306 BloomFilter<?> that = (BloomFilter<?>) object; 307 return this.numHashFunctions == that.numHashFunctions 308 && this.funnel.equals(that.funnel) 309 && this.bits.equals(that.bits) 310 && this.strategy.equals(that.strategy); 311 } 312 return false; 313 } 314 315 @Override 316 public int hashCode() { 317 return Objects.hashCode(numHashFunctions, funnel, strategy, bits); 318 } 319 320 /** 321 * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link 322 * BloomFilter} with false positive probability 3%. 323 * 324 * <p>Note that if the {@code Collector} receives significantly more elements than specified, the 325 * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive 326 * probability. 327 * 328 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 329 * is. 330 * 331 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 332 * ensuring proper serialization and deserialization, which is important since {@link #equals} 333 * also relies on object identity of funnels. 334 * 335 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 336 * @param expectedInsertions the number of expected insertions to the constructed {@code 337 * BloomFilter}; must be positive 338 * @return a {@code Collector} generating a {@code BloomFilter} of the received elements 339 * @since 23.0 (but only since 33.4.0 in the Android flavor) 340 */ 341 public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( 342 Funnel<? super T> funnel, long expectedInsertions) { 343 return toBloomFilter(funnel, expectedInsertions, 0.03); 344 } 345 346 /** 347 * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link 348 * BloomFilter} with the specified expected false positive probability. 349 * 350 * <p>Note that if the {@code Collector} receives significantly more elements than specified, the 351 * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive 352 * probability. 353 * 354 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 355 * is. 356 * 357 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 358 * ensuring proper serialization and deserialization, which is important since {@link #equals} 359 * also relies on object identity of funnels. 360 * 361 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 362 * @param expectedInsertions the number of expected insertions to the constructed {@code 363 * BloomFilter}; must be positive 364 * @param fpp the desired false positive probability (must be positive and less than 1.0) 365 * @return a {@code Collector} generating a {@code BloomFilter} of the received elements 366 * @since 23.0 (but only since 33.4.0 in the Android flavor) 367 */ 368 public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( 369 Funnel<? super T> funnel, long expectedInsertions, double fpp) { 370 checkNotNull(funnel); 371 checkArgument( 372 expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); 373 checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); 374 checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); 375 return Collector.of( 376 () -> BloomFilter.create(funnel, expectedInsertions, fpp), 377 BloomFilter::put, 378 (bf1, bf2) -> { 379 bf1.putAll(bf2); 380 return bf1; 381 }, 382 Collector.Characteristics.UNORDERED, 383 Collector.Characteristics.CONCURRENT); 384 } 385 386 /** 387 * Creates a {@link BloomFilter} with the expected number of insertions and expected false 388 * positive probability. 389 * 390 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 391 * will result in its saturation, and a sharp deterioration of its false positive probability. 392 * 393 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 394 * is. 395 * 396 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 397 * ensuring proper serialization and deserialization, which is important since {@link #equals} 398 * also relies on object identity of funnels. 399 * 400 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 401 * @param expectedInsertions the number of expected insertions to the constructed {@code 402 * BloomFilter}; must be positive 403 * @param fpp the desired false positive probability (must be positive and less than 1.0) 404 * @return a {@code BloomFilter} 405 */ 406 public static <T extends @Nullable Object> BloomFilter<T> create( 407 Funnel<? super T> funnel, int expectedInsertions, double fpp) { 408 return create(funnel, (long) expectedInsertions, fpp); 409 } 410 411 /** 412 * Creates a {@link BloomFilter} with the expected number of insertions and expected false 413 * positive probability. 414 * 415 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 416 * will result in its saturation, and a sharp deterioration of its false positive probability. 417 * 418 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 419 * is. 420 * 421 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 422 * ensuring proper serialization and deserialization, which is important since {@link #equals} 423 * also relies on object identity of funnels. 424 * 425 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 426 * @param expectedInsertions the number of expected insertions to the constructed {@code 427 * BloomFilter}; must be positive 428 * @param fpp the desired false positive probability (must be positive and less than 1.0) 429 * @return a {@code BloomFilter} 430 * @since 19.0 431 */ 432 public static <T extends @Nullable Object> BloomFilter<T> create( 433 Funnel<? super T> funnel, long expectedInsertions, double fpp) { 434 return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64); 435 } 436 437 @VisibleForTesting 438 static <T extends @Nullable Object> BloomFilter<T> create( 439 Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) { 440 checkNotNull(funnel); 441 checkArgument( 442 expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); 443 checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); 444 checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); 445 checkNotNull(strategy); 446 447 if (expectedInsertions == 0) { 448 expectedInsertions = 1; 449 } 450 /* 451 * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size 452 * is proportional to -log(p), but there is not much of a point after all, e.g. 453 * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares! 454 */ 455 long numBits = optimalNumOfBits(expectedInsertions, fpp); 456 int numHashFunctions = optimalNumOfHashFunctions(fpp); 457 try { 458 return new BloomFilter<>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy); 459 } catch (IllegalArgumentException e) { 460 throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); 461 } 462 } 463 464 /** 465 * Creates a {@link BloomFilter} with the expected number of insertions and a default expected 466 * false positive probability of 3%. 467 * 468 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 469 * will result in its saturation, and a sharp deterioration of its false positive probability. 470 * 471 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 472 * is. 473 * 474 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 475 * ensuring proper serialization and deserialization, which is important since {@link #equals} 476 * also relies on object identity of funnels. 477 * 478 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 479 * @param expectedInsertions the number of expected insertions to the constructed {@code 480 * BloomFilter}; must be positive 481 * @return a {@code BloomFilter} 482 */ 483 public static <T extends @Nullable Object> BloomFilter<T> create( 484 Funnel<? super T> funnel, int expectedInsertions) { 485 return create(funnel, (long) expectedInsertions); 486 } 487 488 /** 489 * Creates a {@link BloomFilter} with the expected number of insertions and a default expected 490 * false positive probability of 3%. 491 * 492 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 493 * will result in its saturation, and a sharp deterioration of its false positive probability. 494 * 495 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 496 * is. 497 * 498 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 499 * ensuring proper serialization and deserialization, which is important since {@link #equals} 500 * also relies on object identity of funnels. 501 * 502 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 503 * @param expectedInsertions the number of expected insertions to the constructed {@code 504 * BloomFilter}; must be positive 505 * @return a {@code BloomFilter} 506 * @since 19.0 507 */ 508 public static <T extends @Nullable Object> BloomFilter<T> create( 509 Funnel<? super T> funnel, long expectedInsertions) { 510 return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions 511 } 512 513 // Cheat sheet: 514 // 515 // m: total bits 516 // n: expected insertions 517 // b: m/n, bits per insertion 518 // p: expected false positive probability 519 // 520 // 1) Optimal k = b * ln2 521 // 2) p = (1 - e ^ (-kn/m))^k 522 // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b 523 // 4) For optimal k: m = -nlnp / ((ln2) ^ 2) 524 525 /** 526 * Computes the optimal number of hash functions (k) for a given false positive probability (p). 527 * 528 * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. 529 * 530 * @param p desired false positive probability (must be between 0 and 1, exclusive) 531 */ 532 @VisibleForTesting 533 static int optimalNumOfHashFunctions(double p) { 534 // -log(p) / log(2), ensuring the result is rounded to avoid truncation. 535 return max(1, (int) Math.round(-Math.log(p) / LOG_TWO)); 536 } 537 538 /** 539 * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified 540 * expected insertions, the required false positive probability. 541 * 542 * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the 543 * formula. 544 * 545 * @param n expected insertions (must be positive) 546 * @param p false positive rate (must be 0 < p < 1) 547 */ 548 @VisibleForTesting 549 static long optimalNumOfBits(long n, double p) { 550 if (p == 0) { 551 p = Double.MIN_VALUE; 552 } 553 return (long) (-n * Math.log(p) / SQUARED_LOG_TWO); 554 } 555 556 private Object writeReplace() { 557 return new SerialForm<T>(this); 558 } 559 560 private void readObject(ObjectInputStream stream) throws InvalidObjectException { 561 throw new InvalidObjectException("Use SerializedForm"); 562 } 563 564 private static class SerialForm<T extends @Nullable Object> implements Serializable { 565 final long[] data; 566 final int numHashFunctions; 567 final Funnel<? super T> funnel; 568 final Strategy strategy; 569 570 SerialForm(BloomFilter<T> bf) { 571 this.data = LockFreeBitArray.toPlainArray(bf.bits.data); 572 this.numHashFunctions = bf.numHashFunctions; 573 this.funnel = bf.funnel; 574 this.strategy = bf.strategy; 575 } 576 577 Object readResolve() { 578 return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy); 579 } 580 581 private static final long serialVersionUID = 1; 582 } 583 584 /** 585 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java 586 * serialization). This has been measured to save at least 400 bytes compared to regular 587 * serialization. 588 * 589 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter. 590 */ 591 public void writeTo(OutputStream out) throws IOException { 592 // Serial form: 593 // 1 signed byte for the strategy 594 // 1 unsigned byte for the number of hash functions 595 // 1 big endian int, the number of longs in our bitset 596 // N big endian longs of our bitset 597 DataOutputStream dout = new DataOutputStream(out); 598 dout.writeByte(SignedBytes.checkedCast(strategy.ordinal())); 599 dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor 600 dout.writeInt(bits.data.length()); 601 for (int i = 0; i < bits.data.length(); i++) { 602 dout.writeLong(bits.data.get(i)); 603 } 604 } 605 606 /** 607 * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code 608 * BloomFilter}. 609 * 610 * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here. 611 * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate 612 * the original Bloom filter! 613 * 614 * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not 615 * appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method. 616 */ 617 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 618 public static <T extends @Nullable Object> BloomFilter<T> readFrom( 619 InputStream in, Funnel<? super T> funnel) throws IOException { 620 checkNotNull(in, "InputStream"); 621 checkNotNull(funnel, "Funnel"); 622 int strategyOrdinal = -1; 623 int numHashFunctions = -1; 624 int dataLength = -1; 625 try { 626 DataInputStream din = new DataInputStream(in); 627 // currently this assumes there is no negative ordinal; will have to be updated if we 628 // add non-stateless strategies (for which we've reserved negative ordinals; see 629 // Strategy.ordinal()). 630 strategyOrdinal = din.readByte(); 631 numHashFunctions = UnsignedBytes.toInt(din.readByte()); 632 dataLength = din.readInt(); 633 634 /* 635 * We document in BloomFilterStrategies that we must not change the ordering, and we have a 636 * test that verifies that we don't do so. 637 */ 638 @SuppressWarnings("EnumOrdinal") 639 Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal]; 640 641 LockFreeBitArray dataArray = new LockFreeBitArray(LongMath.checkedMultiply(dataLength, 64L)); 642 for (int i = 0; i < dataLength; i++) { 643 dataArray.putData(i, din.readLong()); 644 } 645 646 return new BloomFilter<>(dataArray, numHashFunctions, funnel, strategy); 647 } catch (IOException e) { 648 throw e; 649 } catch (Exception e) { // sneaky checked exception 650 String message = 651 "Unable to deserialize BloomFilter from InputStream." 652 + " strategyOrdinal: " 653 + strategyOrdinal 654 + " numHashFunctions: " 655 + numHashFunctions 656 + " dataLength: " 657 + dataLength; 658 throw new IOException(message, e); 659 } 660 } 661 662 private static final long serialVersionUID = 0xcafebabe; 663}