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