You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by GitBox <gi...@apache.org> on 2022/08/04 08:16:20 UTC

[GitHub] [commons-collections] aherbert commented on a diff in pull request #320: Collections 824: Optimize SimpleHasher.forEachIndex and SimpleHasher name change

aherbert commented on code in PR #320:
URL: https://github.com/apache/commons-collections/pull/320#discussion_r937459355


##########
src/main/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a> using the enhanced double hashing technique
+ * described in the wikipedia article  <a href="https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing">Double Hashing</a>.
+ * <p>
+ * Common use for this hasher is to generate bit indices from a byte array output of a hashing
+ * or MessageDigest algorithm.</p>
+ *
+ * <h2>Thoughts on the hasher input</h2>
+ *
+ *<p>Note that it is worse to create smaller numbers for the <code>initial</code> and <code>increment</code>. If the <code>initial</code> is smaller than
+ * the number of bits in a filter then hashing will start at the same point when the size increases; likewise the <code>increment</code> will be
+ * the same if it remains smaller than the number of bits in the filter and so the first few indices will be the same if the number of bits
+ * changes (but is still larger than the <code>increment</code>). In a worse case scenario with small <code>initial</code> and <code>increment</code> for
+ * all items, hashing may not create indices that fill the full region within a much larger filter. Imagine hashers created with <code>initial</code>
+ * and <code>increment</code> values less than 255 with a filter size of 30000 and number of hash functions as 5. Ignoring the
+ * tetrahedral addition (a maximum of 20 for k=5) the max index is 255 * 4 + 255 = 1275, this covers 4.25% of the filter. This also
+ * ignores the negative wrapping but the behaviour is the same, some bits cannot be reached.
+ * </p><p>
+ * So this needs to be avoided as the filter probability assumptions will be void. If the <code>initial</code> and <code>increment</code> are larger
+ * than the number of bits then the modulus will create a 'random' position and increment within the size.
+ * </p>
+ *
+ * @since 4.5
+ */
+public class EnhancedDoubleHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Convert bytes to big-endian long filling with zero bytes as necessary..
+     * @param byteArray the byte array to extract the values from.
+     * @param offset the offset to start extraction from.
+     * @param len the length of the extraction, may be longer than 8.
+     * @return
+     */
+    private static long toLong(byte[] byteArray, int offset, int len) {
+        long val = 0;
+        len = Math.min(len, Long.BYTES);
+        int shift = Long.SIZE;
+        for (int i = 0; i < len; i++) {
+            shift -=  Byte.SIZE;
+            val |= ((long) (byteArray[offset + i] & 0x00FF) << shift);

Review Comment:
   `0xff` or `0xFF`: no need for the leading zeros



##########
src/main/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a> using the enhanced double hashing technique
+ * described in the wikipedia article  <a href="https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing">Double Hashing</a>.
+ * <p>
+ * Common use for this hasher is to generate bit indices from a byte array output of a hashing
+ * or MessageDigest algorithm.</p>
+ *
+ * <h2>Thoughts on the hasher input</h2>
+ *
+ *<p>Note that it is worse to create smaller numbers for the <code>initial</code> and <code>increment</code>. If the <code>initial</code> is smaller than
+ * the number of bits in a filter then hashing will start at the same point when the size increases; likewise the <code>increment</code> will be
+ * the same if it remains smaller than the number of bits in the filter and so the first few indices will be the same if the number of bits
+ * changes (but is still larger than the <code>increment</code>). In a worse case scenario with small <code>initial</code> and <code>increment</code> for
+ * all items, hashing may not create indices that fill the full region within a much larger filter. Imagine hashers created with <code>initial</code>
+ * and <code>increment</code> values less than 255 with a filter size of 30000 and number of hash functions as 5. Ignoring the
+ * tetrahedral addition (a maximum of 20 for k=5) the max index is 255 * 4 + 255 = 1275, this covers 4.25% of the filter. This also
+ * ignores the negative wrapping but the behaviour is the same, some bits cannot be reached.
+ * </p><p>
+ * So this needs to be avoided as the filter probability assumptions will be void. If the <code>initial</code> and <code>increment</code> are larger
+ * than the number of bits then the modulus will create a 'random' position and increment within the size.
+ * </p>
+ *
+ * @since 4.5
+ */
+public class EnhancedDoubleHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Convert bytes to big-endian long filling with zero bytes as necessary..
+     * @param byteArray the byte array to extract the values from.
+     * @param offset the offset to start extraction from.
+     * @param len the length of the extraction, may be longer than 8.
+     * @return
+     */
+    private static long toLong(byte[] byteArray, int offset, int len) {
+        long val = 0;
+        len = Math.min(len, Long.BYTES);

Review Comment:
   Directly iterate over the index?:
   ```Java
           final int end = offset + Math.min(len, Long.BYTES);
           for (int i = offset; i < end; i++) {
   ```



##########
src/main/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a> using the enhanced double hashing technique
+ * described in the wikipedia article  <a href="https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing">Double Hashing</a>.
+ * <p>
+ * Common use for this hasher is to generate bit indices from a byte array output of a hashing
+ * or MessageDigest algorithm.</p>
+ *
+ * <h2>Thoughts on the hasher input</h2>
+ *
+ *<p>Note that it is worse to create smaller numbers for the <code>initial</code> and <code>increment</code>. If the <code>initial</code> is smaller than

Review Comment:
   Use `{@code ...}` tags



##########
src/test/java/org/apache/commons/collections4/bloomfilter/AbstractHasherTest.java:
##########
@@ -74,16 +77,28 @@ public void testHashing(int k, int m) {
         });
         assertEquals(k * getHasherSize(hasher), count[0],
                 () -> String.format("Did not produce k=%d * m=%d indices", k, getHasherSize(hasher)));
+
+        // test early exit
+        count[0] = 0;
+        hasher.indices(Shape.fromKM(k, m)).forEachIndex(i -> {
+            assertTrue(i >= 0 && i < m, () -> "Out of range: " + i + ", m=" + m);
+            count[0]++;
+            return false;
+        });
+        assertEquals(1, count[0], "did not exit early" );
     }
 
     @Test
     public void testUniqueIndex() {
-        // create a hasher that produces duplicates with the specified shape.
-        // this setup produces 5, 17, 29, 41, 53, 65 two times
-        Shape shape = Shape.fromKM(12, 72);
-        Hasher hasher = new SimpleHasher(5, 12);
-        Set<Integer> set = new HashSet<>();
-        assertTrue(hasher.uniqueIndices(shape).forEachIndex(set::add), "Duplicate detected");
-        assertEquals(6, set.size());
+        // generating 11 numbers in the ragne of [0,9] will yield at least on collision.

Review Comment:
   `range`



##########
src/test/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasherTest.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests the {@link EnhancedDoubleHasher}.
+ */
+public class EnhancedDoubleHasherTest extends AbstractHasherTest {
+
+    @Override
+    protected Hasher createHasher() {
+        return new EnhancedDoubleHasher(1, 1);
+    }
+
+    @Override
+    protected Hasher createEmptyHasher() {
+        return NullHasher.INSTANCE;
+    }
+
+    @Override
+    protected int getHasherSize(Hasher hasher) {
+        return 1;
+    }
+
+    @Test
+    public void testConstructor() {

Review Comment:
   testByteConstructor



##########
src/main/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a> using the enhanced double hashing technique
+ * described in the wikipedia article  <a href="https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing">Double Hashing</a>.
+ * <p>
+ * Common use for this hasher is to generate bit indices from a byte array output of a hashing
+ * or MessageDigest algorithm.</p>
+ *
+ * <h2>Thoughts on the hasher input</h2>
+ *
+ *<p>Note that it is worse to create smaller numbers for the <code>initial</code> and <code>increment</code>. If the <code>initial</code> is smaller than
+ * the number of bits in a filter then hashing will start at the same point when the size increases; likewise the <code>increment</code> will be
+ * the same if it remains smaller than the number of bits in the filter and so the first few indices will be the same if the number of bits
+ * changes (but is still larger than the <code>increment</code>). In a worse case scenario with small <code>initial</code> and <code>increment</code> for
+ * all items, hashing may not create indices that fill the full region within a much larger filter. Imagine hashers created with <code>initial</code>
+ * and <code>increment</code> values less than 255 with a filter size of 30000 and number of hash functions as 5. Ignoring the
+ * tetrahedral addition (a maximum of 20 for k=5) the max index is 255 * 4 + 255 = 1275, this covers 4.25% of the filter. This also
+ * ignores the negative wrapping but the behaviour is the same, some bits cannot be reached.
+ * </p><p>
+ * So this needs to be avoided as the filter probability assumptions will be void. If the <code>initial</code> and <code>increment</code> are larger
+ * than the number of bits then the modulus will create a 'random' position and increment within the size.
+ * </p>
+ *
+ * @since 4.5
+ */
+public class EnhancedDoubleHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Convert bytes to big-endian long filling with zero bytes as necessary..
+     * @param byteArray the byte array to extract the values from.
+     * @param offset the offset to start extraction from.
+     * @param len the length of the extraction, may be longer than 8.
+     * @return
+     */
+    private static long toLong(byte[] byteArray, int offset, int len) {
+        long val = 0;
+        len = Math.min(len, Long.BYTES);
+        int shift = Long.SIZE;
+        for (int i = 0; i < len; i++) {
+            shift -=  Byte.SIZE;
+            val |= ((long) (byteArray[offset + i] & 0x00FF) << shift);
+        }
+        return val;
+    }
+
+    /**
+     * Constructs the EnhancedDoubleHasher from a byte array.
+     * <p>
+     * This method simplifies the conversion from a Digest or hasher algorithm output
+     * to the two values used by the EnhancedDoubleHasher.</p>
+     * <p>The byte array is split in 2 and the first 8 bytes of each half are interpreted as a big-endian long value.
+     * Excess bytes are ignored.
+     * If there are fewer than 16 bytes the following conversions are made.
+     *</p>
+     * <ol>
+     * <li>If there is an odd number of bytes the excess byte is assigned to the increment value</li>
+     * <li>The bytes alloted are read in big-endian order any byte not populated is set to zero.</li>
+     * </ol>
+     * <p>
+     * This ensures that small arrays generate the largest possible increment and initial values.
+     * </p>
+     * @param buffer the buffer to extract the longs from.
+     * @throws IllegalArgumentException is buffer length is zero.
+     */
+    public EnhancedDoubleHasher(byte[] buffer) {
+        if (buffer.length == 0) {
+            throw new IllegalArgumentException("buffer length must be greater than 0");
+        }
+        // divide by 2
+        int segment = buffer.length / 2;
+        this.initial = toLong(buffer, 0, segment);
+        this.increment = toLong(buffer, segment, buffer.length - segment);
+    }
+
+    /**
+     * Constructs the EnhancedDoubleHasher from 2 longs.  The long values will be interpreted as unsigned values.
+     * @param initial The initial value for the hasher.
+     * @param increment The value to increment the hash by on each iteration.
+     */
+    public EnhancedDoubleHasher(long initial, long increment) {
+        this.initial = initial;
+        this.increment = increment;
+    }
+
+    /**
+     * Gets the initial value for the hash calculation.
+     * @return the initial value for the hash calculation.
+     */
+    long getInitial() {
+        return initial;
+    }
+
+    /**
+     * Gets the increment value for the hash calculation.
+     * @return the increment value for the hash calculation.
+     */
+    long getIncrement() {
+        return increment;
+    }
+
+    /**
+     * Performs a modulus calculation on an unsigned long and an integer divisor.
+     * @param dividend a unsigned long value to calculate the modulus of.
+     * @param divisor the divisor for the modulus calculation.
+     * @return the remainder or modulus value.
+     */
+    static int mod(long dividend, int divisor) {
+        // See Hacker's Delight (2nd ed), section 9.3.
+        // Assume divisor is positive.
+        // Divide half the unsigned number and then double the quotient result.
+        final long quotient = ((dividend >>> 1) / divisor) << 1;
+        final long remainder = dividend - quotient * divisor;
+        // remainder in [0, 2 * divisor)
+        return (int) (remainder >= divisor ? remainder - divisor : remainder);
+    }
+
+    @Override
+    public IndexProducer indices(final Shape shape) {
+        Objects.requireNonNull(shape, "shape");
+
+        return new IndexProducer() {
+
+            @Override
+            public boolean forEachIndex(IntPredicate consumer) {
+                Objects.requireNonNull(consumer, "consumer");
+                final int bits = shape.getNumberOfBits();
+                // Enhanced double hashing:
+                // hash[i] = ( h1(x) + i*h2(x) + (i*i*i - i)/6 ) mod bits
+                // See: https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing
+                //
+                // Essentially this is computing a wrapped modulus from a start point and an
+                // increment and an additional term as a tetrahedral number.
+                // You only need two modulus operations before the loop. Within the loop
+                // the modulus is handled using the sign bit to detect wrapping to ensure:
+                // 0 <= index < bits
+                // 0 <= inc < bits
+                // The final hash is:
+                // hash[i] = ( h1(x) - i*h2(x) - (i*i*i - i)/6 ) wrapped in [0, bits)
+
+                int index = mod(initial, bits);
+                int inc = mod(increment, bits);
+
+                final int k = shape.getNumberOfHashFunctions();
+                if (k > bits) {
+                    for (int j = k; j > 0;) {
+                        // handle k > bits
+                        final int block = Math.min(j, bits);
+                        j -= block;
+                        for (int i = 0; i < block; i++) {
+                            if (!consumer.test(index)) {
+                                return false;
+                            }
+                            // Update index and handle wrapping
+                            index -= inc;
+                            index = index < 0 ? index + bits : index;
+
+                            // Incorporate the counter into the increment to create a
+                            // tetrahedral number additional term, and handle wrapping.
+                            inc -= i;
+                            inc = inc < 0 ? inc + bits : inc;
+                        }
+                    }
+                } else {
+                    for (int i = 0; i < k; i++) {
+                        if (!consumer.test(index)) {
+                            return false;
+                        }
+                        // Update index and handle wrapping
+                        index -= inc;
+                        index = index < 0 ? index + bits : index;
+
+                        // Incorporate the counter into the increment to create a
+                        // tetrahedral number additional term, and handle wrapping.
+                        inc -= i;
+                        inc = inc < 0 ? inc + bits : inc;
+                    }
+

Review Comment:
   Remove extra blank line



##########
src/test/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasherTest.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests the {@link EnhancedDoubleHasher}.
+ */
+public class EnhancedDoubleHasherTest extends AbstractHasherTest {
+
+    @Override
+    protected Hasher createHasher() {
+        return new EnhancedDoubleHasher(1, 1);
+    }
+
+    @Override
+    protected Hasher createEmptyHasher() {
+        return NullHasher.INSTANCE;
+    }
+
+    @Override
+    protected int getHasherSize(Hasher hasher) {
+        return 1;
+    }
+
+    @Test
+    public void testConstructor() {
+        // single value become increment.
+        EnhancedDoubleHasher hasher = new EnhancedDoubleHasher( new byte[] { 1 } );
+        assertEquals( 0, hasher.getInitial() );
+        assertEquals( 0x100000000000000L, hasher.getIncrement() );

Review Comment:
   In this test It may be useful to have the leading zero. You can break up the constants using underscores:
   ```
   0x0100_0000_0000_0000L
   ```
   This makes it more readable. Typically using `_` every 2 bytes is common but here we could use every byte:
   ```
   0x01_00_00_00_00_00_00_00L
   ```



##########
src/test/java/org/apache/commons/collections4/bloomfilter/IncrementingHasher.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements simple combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a>.
+ *
+ * <p>To be used for testing only.</p>
+ *
+ * @since 4.5
+ */
+class IncrementingHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Constructs the IncrementingHasher from 2 longs.  The long values will be interpreted as unsigned values.
+     * <p>
+     * The initial hash value will be the modulus of the initial value.
+     * Subsequent values will be calculated by repeatedly adding the increment to the last value and taking the modulus.
+     * </p>
+     * @param initial The initial value for the hasher.
+     * @param increment The value to increment the hash by on each iteration.
+     * @see #getDefaultIncrement()

Review Comment:
   The reference to `getDefaultIncrement()` is still present.



##########
src/test/java/org/apache/commons/collections4/bloomfilter/IncrementingHasher.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements simple combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a>.
+ *
+ * <p>To be used for testing only.</p>
+ *
+ * @since 4.5
+ */
+class IncrementingHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Constructs the IncrementingHasher from 2 longs.  The long values will be interpreted as unsigned values.
+     * <p>
+     * The initial hash value will be the modulus of the initial value.
+     * Subsequent values will be calculated by repeatedly adding the increment to the last value and taking the modulus.
+     * </p>
+     * @param initial The initial value for the hasher.
+     * @param increment The value to increment the hash by on each iteration.
+     * @see #getDefaultIncrement()
+     */
+    IncrementingHasher(long initial, long increment) {
+        this.initial = initial;
+        this.increment = increment;
+    }
+
+    @Override
+    public IndexProducer indices(final Shape shape) {
+        Objects.requireNonNull(shape, "shape");
+
+        return new IndexProducer() {
+
+            @Override
+            public boolean forEachIndex(IntPredicate consumer) {
+                Objects.requireNonNull(consumer, "consumer");
+                int bits = shape.getNumberOfBits();
+                /*
+                 * Essentially this is computing a wrapped modulus from a start point and an
+                 * increment. So actually you only need two modulus operations before the loop.
+                 * This avoids any modulus operation inside the while loop. It uses a long index
+                 * to avoid overflow.
+                 */
+                long index = EnhancedDoubleHasher.mod(initial, bits);
+                int inc = EnhancedDoubleHasher.mod(increment, bits);
+
+                for (int functionalCount = 0; functionalCount < shape.getNumberOfHashFunctions(); functionalCount++) {
+

Review Comment:
   Remove extra line



##########
src/test/java/org/apache/commons/collections4/bloomfilter/IncrementingHasher.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements simple combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a>.
+ *
+ * <p>To be used for testing only.</p>
+ *
+ * @since 4.5
+ */
+class IncrementingHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Constructs the IncrementingHasher from 2 longs.  The long values will be interpreted as unsigned values.
+     * <p>
+     * The initial hash value will be the modulus of the initial value.
+     * Subsequent values will be calculated by repeatedly adding the increment to the last value and taking the modulus.
+     * </p>
+     * @param initial The initial value for the hasher.
+     * @param increment The value to increment the hash by on each iteration.
+     * @see #getDefaultIncrement()
+     */
+    IncrementingHasher(long initial, long increment) {
+        this.initial = initial;
+        this.increment = increment;
+    }
+
+    @Override
+    public IndexProducer indices(final Shape shape) {
+        Objects.requireNonNull(shape, "shape");
+
+        return new IndexProducer() {
+
+            @Override
+            public boolean forEachIndex(IntPredicate consumer) {
+                Objects.requireNonNull(consumer, "consumer");
+                int bits = shape.getNumberOfBits();
+                /*
+                 * Essentially this is computing a wrapped modulus from a start point and an

Review Comment:
   Change c-style comment to a Java block comment (using `//`)



##########
src/main/java/org/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a> using the enhanced double hashing technique
+ * described in the wikipedia article  <a href="https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing">Double Hashing</a>.
+ * <p>
+ * Common use for this hasher is to generate bit indices from a byte array output of a hashing
+ * or MessageDigest algorithm.</p>
+ *
+ * <h2>Thoughts on the hasher input</h2>
+ *
+ *<p>Note that it is worse to create smaller numbers for the <code>initial</code> and <code>increment</code>. If the <code>initial</code> is smaller than
+ * the number of bits in a filter then hashing will start at the same point when the size increases; likewise the <code>increment</code> will be
+ * the same if it remains smaller than the number of bits in the filter and so the first few indices will be the same if the number of bits
+ * changes (but is still larger than the <code>increment</code>). In a worse case scenario with small <code>initial</code> and <code>increment</code> for
+ * all items, hashing may not create indices that fill the full region within a much larger filter. Imagine hashers created with <code>initial</code>
+ * and <code>increment</code> values less than 255 with a filter size of 30000 and number of hash functions as 5. Ignoring the
+ * tetrahedral addition (a maximum of 20 for k=5) the max index is 255 * 4 + 255 = 1275, this covers 4.25% of the filter. This also
+ * ignores the negative wrapping but the behaviour is the same, some bits cannot be reached.
+ * </p><p>
+ * So this needs to be avoided as the filter probability assumptions will be void. If the <code>initial</code> and <code>increment</code> are larger
+ * than the number of bits then the modulus will create a 'random' position and increment within the size.
+ * </p>
+ *
+ * @since 4.5
+ */
+public class EnhancedDoubleHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Convert bytes to big-endian long filling with zero bytes as necessary..
+     * @param byteArray the byte array to extract the values from.
+     * @param offset the offset to start extraction from.
+     * @param len the length of the extraction, may be longer than 8.
+     * @return
+     */
+    private static long toLong(byte[] byteArray, int offset, int len) {
+        long val = 0;
+        len = Math.min(len, Long.BYTES);
+        int shift = Long.SIZE;
+        for (int i = 0; i < len; i++) {
+            shift -=  Byte.SIZE;
+            val |= ((long) (byteArray[offset + i] & 0x00FF) << shift);
+        }
+        return val;
+    }
+
+    /**
+     * Constructs the EnhancedDoubleHasher from a byte array.
+     * <p>
+     * This method simplifies the conversion from a Digest or hasher algorithm output
+     * to the two values used by the EnhancedDoubleHasher.</p>
+     * <p>The byte array is split in 2 and the first 8 bytes of each half are interpreted as a big-endian long value.
+     * Excess bytes are ignored.
+     * If there are fewer than 16 bytes the following conversions are made.
+     *</p>
+     * <ol>
+     * <li>If there is an odd number of bytes the excess byte is assigned to the increment value</li>
+     * <li>The bytes alloted are read in big-endian order any byte not populated is set to zero.</li>
+     * </ol>
+     * <p>
+     * This ensures that small arrays generate the largest possible increment and initial values.
+     * </p>
+     * @param buffer the buffer to extract the longs from.
+     * @throws IllegalArgumentException is buffer length is zero.
+     */
+    public EnhancedDoubleHasher(byte[] buffer) {
+        if (buffer.length == 0) {
+            throw new IllegalArgumentException("buffer length must be greater than 0");
+        }
+        // divide by 2
+        int segment = buffer.length / 2;
+        this.initial = toLong(buffer, 0, segment);
+        this.increment = toLong(buffer, segment, buffer.length - segment);
+    }
+
+    /**
+     * Constructs the EnhancedDoubleHasher from 2 longs.  The long values will be interpreted as unsigned values.
+     * @param initial The initial value for the hasher.
+     * @param increment The value to increment the hash by on each iteration.
+     */
+    public EnhancedDoubleHasher(long initial, long increment) {
+        this.initial = initial;
+        this.increment = increment;
+    }
+
+    /**
+     * Gets the initial value for the hash calculation.
+     * @return the initial value for the hash calculation.
+     */
+    long getInitial() {
+        return initial;
+    }
+
+    /**
+     * Gets the increment value for the hash calculation.
+     * @return the increment value for the hash calculation.
+     */
+    long getIncrement() {
+        return increment;
+    }
+
+    /**
+     * Performs a modulus calculation on an unsigned long and an integer divisor.
+     * @param dividend a unsigned long value to calculate the modulus of.
+     * @param divisor the divisor for the modulus calculation.
+     * @return the remainder or modulus value.
+     */
+    static int mod(long dividend, int divisor) {
+        // See Hacker's Delight (2nd ed), section 9.3.
+        // Assume divisor is positive.
+        // Divide half the unsigned number and then double the quotient result.
+        final long quotient = ((dividend >>> 1) / divisor) << 1;
+        final long remainder = dividend - quotient * divisor;
+        // remainder in [0, 2 * divisor)
+        return (int) (remainder >= divisor ? remainder - divisor : remainder);
+    }
+
+    @Override
+    public IndexProducer indices(final Shape shape) {
+        Objects.requireNonNull(shape, "shape");
+
+        return new IndexProducer() {
+
+            @Override
+            public boolean forEachIndex(IntPredicate consumer) {
+                Objects.requireNonNull(consumer, "consumer");
+                final int bits = shape.getNumberOfBits();
+                // Enhanced double hashing:
+                // hash[i] = ( h1(x) + i*h2(x) + (i*i*i - i)/6 ) mod bits
+                // See: https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing
+                //
+                // Essentially this is computing a wrapped modulus from a start point and an
+                // increment and an additional term as a tetrahedral number.
+                // You only need two modulus operations before the loop. Within the loop
+                // the modulus is handled using the sign bit to detect wrapping to ensure:
+                // 0 <= index < bits
+                // 0 <= inc < bits
+                // The final hash is:
+                // hash[i] = ( h1(x) - i*h2(x) - (i*i*i - i)/6 ) wrapped in [0, bits)
+
+                int index = mod(initial, bits);
+                int inc = mod(increment, bits);
+
+                final int k = shape.getNumberOfHashFunctions();
+                if (k > bits) {
+                    for (int j = k; j > 0;) {
+                        // handle k > bits
+                        final int block = Math.min(j, bits);
+                        j -= block;
+                        for (int i = 0; i < block; i++) {
+                            if (!consumer.test(index)) {
+                                return false;
+                            }
+                            // Update index and handle wrapping
+                            index -= inc;
+                            index = index < 0 ? index + bits : index;
+
+                            // Incorporate the counter into the increment to create a
+                            // tetrahedral number additional term, and handle wrapping.
+                            inc -= i;
+                            inc = inc < 0 ? inc + bits : inc;
+                        }
+                    }
+                } else {
+                    for (int i = 0; i < k; i++) {
+                        if (!consumer.test(index)) {
+                            return false;
+                        }
+                        // Update index and handle wrapping
+                        index -= inc;
+                        index = index < 0 ? index + bits : index;
+
+                        // Incorporate the counter into the increment to create a
+                        // tetrahedral number additional term, and handle wrapping.
+                        inc -= i;
+                        inc = inc < 0 ? inc + bits : inc;
+                    }
+
+                }
+
+                return true;
+            }
+
+            @Override
+            public int[] asIndexArray() {
+                int[] result = new int[shape.getNumberOfHashFunctions()];
+                int[] idx = new int[1];
+                /*
+                 * This method needs to return duplicate indices

Review Comment:
   Change c-style comment to use `// ...`



##########
src/test/java/org/apache/commons/collections4/bloomfilter/IncrementingHasher.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.bloomfilter;
+
+import java.util.Objects;
+import java.util.function.IntPredicate;
+
+/**
+ * A Hasher that implements simple combinatorial hashing as as described by
+ * <a href="https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf">Krisch and Mitzenmacher</a>.
+ *
+ * <p>To be used for testing only.</p>
+ *
+ * @since 4.5
+ */
+class IncrementingHasher implements Hasher {
+
+    /**
+     * The initial hash value.
+     */
+    private final long initial;
+
+    /**
+     * The value to increment the hash value by.
+     */
+    private final long increment;
+
+    /**
+     * Constructs the IncrementingHasher from 2 longs.  The long values will be interpreted as unsigned values.
+     * <p>
+     * The initial hash value will be the modulus of the initial value.
+     * Subsequent values will be calculated by repeatedly adding the increment to the last value and taking the modulus.
+     * </p>
+     * @param initial The initial value for the hasher.
+     * @param increment The value to increment the hash by on each iteration.
+     * @see #getDefaultIncrement()
+     */
+    IncrementingHasher(long initial, long increment) {
+        this.initial = initial;
+        this.increment = increment;
+    }
+
+    @Override
+    public IndexProducer indices(final Shape shape) {
+        Objects.requireNonNull(shape, "shape");
+
+        return new IndexProducer() {
+
+            @Override
+            public boolean forEachIndex(IntPredicate consumer) {
+                Objects.requireNonNull(consumer, "consumer");
+                int bits = shape.getNumberOfBits();
+                /*
+                 * Essentially this is computing a wrapped modulus from a start point and an
+                 * increment. So actually you only need two modulus operations before the loop.
+                 * This avoids any modulus operation inside the while loop. It uses a long index
+                 * to avoid overflow.
+                 */
+                long index = EnhancedDoubleHasher.mod(initial, bits);
+                int inc = EnhancedDoubleHasher.mod(increment, bits);
+
+                for (int functionalCount = 0; functionalCount < shape.getNumberOfHashFunctions(); functionalCount++) {
+
+                    if (!consumer.test((int) index)) {
+                        return false;
+                    }
+                    index += inc;
+                    index = index >= bits ? index - bits : index;
+                }
+                return true;
+            }
+
+            @Override
+            public int[] asIndexArray() {
+                int[] result = new int[shape.getNumberOfHashFunctions()];
+                int[] idx = new int[1];
+                /*

Review Comment:
   Change c-style comment to use `// ...`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org