diff --git a/src/main/java/org/apache/datasketches/cpc/CpcSketch.java b/src/main/java/org/apache/datasketches/cpc/CpcSketch.java index d5e17388a..051ebd9b4 100644 --- a/src/main/java/org/apache/datasketches/cpc/CpcSketch.java +++ b/src/main/java/org/apache/datasketches/cpc/CpcSketch.java @@ -22,14 +22,12 @@ import static java.lang.Math.log; import static java.lang.Math.sqrt; import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.datasketches.common.Util.LS; import static org.apache.datasketches.common.Util.invPow2; import static org.apache.datasketches.common.Util.zeroPad; import static org.apache.datasketches.cpc.CpcUtil.bitMatrixOfSketch; import static org.apache.datasketches.cpc.CpcUtil.checkLgK; import static org.apache.datasketches.cpc.CpcUtil.countBitsSetInMatrix; -import static org.apache.datasketches.hash.MurmurHash3.hash; import java.lang.foreign.MemorySegment; import java.nio.ByteBuffer; @@ -37,6 +35,7 @@ import org.apache.datasketches.common.Family; import org.apache.datasketches.common.Util; +import org.apache.datasketches.hash.ItemHash; /** * This is a unique-counting sketch that implements the @@ -309,9 +308,7 @@ public byte[] toByteArray() { * @param datum The given long datum. */ public void update(final long datum) { - final long[] data = { datum }; - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(datum, seed)); } /** @@ -324,10 +321,7 @@ public void update(final long datum) { * @param datum The given double datum. */ public void update(final double datum) { - final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(datum, seed)); } /** @@ -345,10 +339,7 @@ public void update(final double datum) { * @param datum The given String. */ public void update(final String datum) { - if ((datum == null) || datum.isEmpty()) { return; } - final byte[] data = datum.getBytes(UTF_8); - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(datum, seed)); } /** @@ -358,9 +349,7 @@ public void update(final String datum) { * @param data The given byte array. */ public void update(final byte[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(data, seed)); } /** @@ -370,9 +359,7 @@ public void update(final byte[] data) { * @param data The given ByteBuffer */ public void update(final ByteBuffer data) { - if ((data == null) || !data.hasRemaining()) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(data, seed)); } /** @@ -385,9 +372,7 @@ public void update(final ByteBuffer data) { * @param data The given char array. */ public void update(final char[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(data, seed)); } /** @@ -397,9 +382,7 @@ public void update(final char[] data) { * @param data The given int array. */ public void update(final int[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(data, seed)); } /** @@ -409,9 +392,20 @@ public void update(final int[] data) { * @param data The given long array. */ public void update(final long[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); + update(ItemHash.of(data, seed)); + } + + /** + * Present this sketch with a precomputed item hash, as if updating with the item itself. + * A null hash is ignored. + * + * @param hash the item hash, computed with this sketch's seed + * @throws org.apache.datasketches.common.SketchesArgumentException if the hash was computed with a different seed + */ + public void update(final ItemHash hash) { + if (hash == null) { return; } + hash.checkSeed(seed); + hashUpdate(hash.h0(), hash.h1()); } /** diff --git a/src/main/java/org/apache/datasketches/hash/ItemHash.java b/src/main/java/org/apache/datasketches/hash/ItemHash.java new file mode 100644 index 000000000..9fd95d3f4 --- /dev/null +++ b/src/main/java/org/apache/datasketches/hash/ItemHash.java @@ -0,0 +1,157 @@ +/* + * 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.datasketches.hash; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.lang.foreign.MemorySegment; +import java.nio.ByteBuffer; + +import org.apache.datasketches.common.SketchesArgumentException; + +/** + * The canonicalized 128-bit MurmurHash3 of one update item, together with the seed it was computed with. + * + *

Every hash-based sketch derives its internal value from this hash, so one instance can update + * several sketches that share the seed, producing the same result as updating each with the item. + * The factory methods return null for null or empty items, which sketches ignore.

+ */ +public final class ItemHash { + private final long h0; + private final long h1; + private final long seed; + + private ItemHash(final long[] hash, final long seed) { + this.h0 = hash[0]; + this.h1 = hash[1]; + this.seed = seed; + } + + /** + * Hashes a long. + * @param datum the item + * @param seed the update seed + * @return the item hash + */ + public static ItemHash of(final long datum, final long seed) { + return new ItemHash(MurmurHash3.hash(datum, seed), seed); + } + + /** + * Hashes a double, treating -0.0 as 0.0 and all NaN forms as one value. + * @param datum the item + * @param seed the update seed + * @return the item hash + */ + public static ItemHash of(final double datum, final long seed) { + return of(Double.doubleToLongBits(datum == 0.0 ? 0.0 : datum), seed); + } + + /** + * Hashes the UTF-8 encoding of a String. + * @param datum the item + * @param seed the update seed + * @return the item hash, or null if the item is null or empty + */ + public static ItemHash of(final String datum, final long seed) { + return datum == null || datum.isEmpty() ? null : new ItemHash(MurmurHash3.hash(datum.getBytes(UTF_8), seed), seed); + } + + /** + * Hashes a byte array. + * @param data the item + * @param seed the update seed + * @return the item hash, or null if the item is null or empty + */ + public static ItemHash of(final byte[] data, final long seed) { + return data == null || data.length == 0 ? null : new ItemHash(MurmurHash3.hash(data, seed), seed); + } + + /** + * Hashes a char array. + * @param data the item + * @param seed the update seed + * @return the item hash, or null if the item is null or empty + */ + public static ItemHash of(final char[] data, final long seed) { + return data == null || data.length == 0 ? null : new ItemHash(MurmurHash3.hash(data, seed), seed); + } + + /** + * Hashes an int array. + * @param data the item + * @param seed the update seed + * @return the item hash, or null if the item is null or empty + */ + public static ItemHash of(final int[] data, final long seed) { + return data == null || data.length == 0 ? null : new ItemHash(MurmurHash3.hash(data, seed), seed); + } + + /** + * Hashes a long array. + * @param data the item + * @param seed the update seed + * @return the item hash, or null if the item is null or empty + */ + public static ItemHash of(final long[] data, final long seed) { + return data == null || data.length == 0 ? null : new ItemHash(MurmurHash3.hash(data, seed), seed); + } + + /** + * Hashes the remaining bytes of a ByteBuffer. + * @param data the item + * @param seed the update seed + * @return the item hash, or null if the item is null or has no remaining bytes + */ + public static ItemHash of(final ByteBuffer data, final long seed) { + return data == null || !data.hasRemaining() ? null : new ItemHash(MurmurHash3.hash(data, seed), seed); + } + + /** + * Hashes the bytes of a MemorySegment. + * @param data the item + * @param seed the update seed + * @return the item hash, or null if the item is null or empty + */ + public static ItemHash of(final MemorySegment data, final long seed) { + return data == null || data.byteSize() == 0 ? null : new ItemHash(MurmurHash3.hash(data, seed), seed); + } + + /** + * Returns the low 64 bits of the hash. + * @return the low 64 bits + */ + public long h0() { return h0; } + + /** + * Returns the high 64 bits of the hash. + * @return the high 64 bits + */ + public long h1() { return h1; } + + /** + * Checks that this hash was computed with the given seed. + * @param seed the seed of the sketch being updated + * @throws SketchesArgumentException if the seeds differ + */ + public void checkSeed(final long seed) { + if (this.seed != seed) { throw new SketchesArgumentException("ItemHash seed does not match the sketch seed"); } + } +} diff --git a/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java b/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java index 99107220e..2c8f68a1c 100644 --- a/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java +++ b/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java @@ -20,8 +20,6 @@ package org.apache.datasketches.hll; import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.hash.MurmurHash3.hash; import static org.apache.datasketches.hll.HllUtil.HLL_HIP_RSE_FACTOR; import static org.apache.datasketches.hll.HllUtil.HLL_NON_HIP_RSE_FACTOR; import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; @@ -32,6 +30,7 @@ import org.apache.datasketches.common.MemorySegmentStatus; import org.apache.datasketches.common.Util; +import org.apache.datasketches.hash.ItemHash; /** * Although this class is package-private, it provides a single place to define and document @@ -303,8 +302,7 @@ public abstract String toString(boolean summary, boolean detail, boolean auxDeta * @param datum The given long datum. */ public void update(final long datum) { - final long[] data = { datum }; - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(datum, Util.DEFAULT_UPDATE_SEED)); } /** @@ -317,9 +315,7 @@ public void update(final long datum) { * @param datum The given double datum. */ public void update(final double datum) { - final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN & +/- infinity forms - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(datum, Util.DEFAULT_UPDATE_SEED)); } /** @@ -337,9 +333,7 @@ public void update(final double datum) { * @param datum The given String. */ public void update(final String datum) { - if ((datum == null) || datum.isEmpty()) { return; } - final byte[] data = datum.getBytes(UTF_8); - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(datum, Util.DEFAULT_UPDATE_SEED)); } /** @@ -355,8 +349,7 @@ public void update(final String datum) { * @param data The given byte buffer. */ public void update(final ByteBuffer data) { - if ((data == null) || (data.remaining() == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(data, Util.DEFAULT_UPDATE_SEED)); } /** @@ -366,8 +359,7 @@ public void update(final ByteBuffer data) { * @param data The given byte array. */ public void update(final byte[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(data, Util.DEFAULT_UPDATE_SEED)); } /** @@ -380,8 +372,7 @@ public void update(final byte[] data) { * @param data The given char array. */ public void update(final char[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(data, Util.DEFAULT_UPDATE_SEED)); } /** @@ -391,8 +382,7 @@ public void update(final char[] data) { * @param data The given int array. */ public void update(final int[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(data, Util.DEFAULT_UPDATE_SEED)); } /** @@ -402,13 +392,25 @@ public void update(final int[] data) { * @param data The given long array. */ public void update(final long[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); + update(ItemHash.of(data, Util.DEFAULT_UPDATE_SEED)); } - private static final int coupon(final long[] hash) { - final int addr26 = (int) ((hash[0] & KEY_MASK_26)); - final int lz = Long.numberOfLeadingZeros(hash[1]); + /** + * Present this sketch with a precomputed item hash, as if updating with the item itself. + * A null hash is ignored. + * + * @param hash the item hash, computed with the default update seed + * @throws org.apache.datasketches.common.SketchesArgumentException if the hash was computed with a different seed + */ + public void update(final ItemHash hash) { + if (hash == null) { return; } + hash.checkSeed(Util.DEFAULT_UPDATE_SEED); + couponUpdate(coupon(hash.h0(), hash.h1())); + } + + private static final int coupon(final long hash0, final long hash1) { + final int addr26 = (int) ((hash0 & KEY_MASK_26)); + final int lz = Long.numberOfLeadingZeros(hash1); final int value = ((lz > 62 ? 62 : lz) + 1); return (value << KEY_BITS_26) | addr26; } diff --git a/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java b/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java index cc6bfd322..c372bc858 100644 --- a/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java +++ b/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java @@ -19,10 +19,8 @@ package org.apache.datasketches.theta; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; import static org.apache.datasketches.common.QuickSelect.select; -import static org.apache.datasketches.hash.MurmurHash3.hash; import static org.apache.datasketches.theta.CompactOperations.componentsToCompact; import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; @@ -48,6 +46,7 @@ import org.apache.datasketches.common.ResizeFactor; import org.apache.datasketches.common.SketchesArgumentException; import org.apache.datasketches.common.Util; +import org.apache.datasketches.hash.ItemHash; import org.apache.datasketches.thetacommon.ThetaUtil; /** @@ -353,7 +352,7 @@ public static final UpdatableThetaSketchBuilder builder() { * See Update Return State */ public UpdateReturnState update(final long datum) { - return hashUpdate(hash(datum, seed_)[0] >>> 1); + return update(ItemHash.of(datum, seed_)); } /** @@ -368,9 +367,7 @@ public UpdateReturnState update(final long datum) { * See Update Return State */ public UpdateReturnState update(final double datum) { - final double d = datum == 0.0 ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long data = Double.doubleToLongBits(d);// canonicalize all NaN & +/- infinity forms - return hashUpdate(hash(data, seed_)[0] >>> 1); + return update(ItemHash.of(datum, seed_)); } /** @@ -387,11 +384,7 @@ public UpdateReturnState update(final double datum) { * See Update Return State */ public UpdateReturnState update(final String datum) { - if (datum == null || datum.isEmpty()) { - return RejectedNullOrEmpty; - } - final byte[] data = datum.getBytes(UTF_8); - return hashUpdate(hash(data, seed_)[0] >>> 1); + return update(ItemHash.of(datum, seed_)); } /** @@ -403,10 +396,7 @@ public UpdateReturnState update(final String datum) { * See Update Return State */ public UpdateReturnState update(final byte[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); + return update(ItemHash.of(data, seed_)); } /** @@ -418,10 +408,7 @@ public UpdateReturnState update(final byte[] data) { * See Update Return State */ public UpdateReturnState update(final ByteBuffer buffer) { - if (buffer == null || !buffer.hasRemaining()) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(buffer, seed_)[0] >>> 1); + return update(ItemHash.of(buffer, seed_)); } /** @@ -436,10 +423,7 @@ public UpdateReturnState update(final ByteBuffer buffer) { * See Update Return State */ public UpdateReturnState update(final char[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); + return update(ItemHash.of(data, seed_)); } /** @@ -451,10 +435,7 @@ public UpdateReturnState update(final char[] data) { * See Update Return State */ public UpdateReturnState update(final int[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); + return update(ItemHash.of(data, seed_)); } /** @@ -466,10 +447,22 @@ public UpdateReturnState update(final int[] data) { * See Update Return State */ public UpdateReturnState update(final long[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); + return update(ItemHash.of(data, seed_)); + } + + /** + * Present this sketch with a precomputed item hash, as if updating with the item itself. + * A null hash is ignored. + * + * @param hash the item hash, computed with this sketch's seed + * @return + * See Update Return State + * @throws org.apache.datasketches.common.SketchesArgumentException if the hash was computed with a different seed + */ + public UpdateReturnState update(final ItemHash hash) { + if (hash == null) { return RejectedNullOrEmpty; } + hash.checkSeed(seed_); + return hashUpdate(hash.h0() >>> 1); } //restricted methods diff --git a/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java b/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java index 373925a97..acba59abe 100644 --- a/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java +++ b/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java @@ -26,7 +26,7 @@ import java.nio.ByteBuffer; import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.hash.MurmurHash3; +import org.apache.datasketches.hash.ItemHash; /** * An extension of QuickSelectSketch<S>, which can be updated with many types of keys. @@ -149,7 +149,7 @@ public byte[] toByteArray() { * @param value The given U value */ public void update(final long key, final U value) { - update(new long[] {key}, value); + update(ItemHash.of(key, seed_), value); } /** @@ -160,7 +160,7 @@ public void update(final long key, final U value) { * @param value The given U value */ public void update(final double key, final U value) { - update(Util.doubleToLongArray(key), value); + update(ItemHash.of(key, seed_), value); } /** @@ -171,7 +171,7 @@ public void update(final double key, final U value) { * @param value The given U value */ public void update(final String key, final U value) { - update(Util.stringToByteArray(key), value); + update(ItemHash.of(key, seed_), value); } /** @@ -182,8 +182,7 @@ public void update(final String key, final U value) { * @param value The given U value */ public void update(final byte[] key, final U value) { - if ((key == null) || (key.length == 0)) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, value); + update(ItemHash.of(key, seed_), value); } /** @@ -194,8 +193,7 @@ public void update(final byte[] key, final U value) { * @param value The given U value */ public void update(final ByteBuffer buffer, final U value) { - if (buffer == null || buffer.hasRemaining() == false) { return; } - insertOrIgnore(MurmurHash3.hash(buffer, seed_)[0] >>> 1, value); + update(ItemHash.of(buffer, seed_), value); } /** @@ -206,8 +204,7 @@ public void update(final ByteBuffer buffer, final U value) { * @param value The given U value */ public void update(final int[] key, final U value) { - if ((key == null) || (key.length == 0)) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, value); + update(ItemHash.of(key, seed_), value); } /** @@ -218,8 +215,21 @@ public void update(final int[] key, final U value) { * @param value The given U value */ public void update(final long[] key, final U value) { - if ((key == null) || (key.length == 0)) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, value); + update(ItemHash.of(key, seed_), value); + } + + /** + * Present this sketch with a precomputed item hash, as if updating with the item itself. + * A null hash is ignored. + * + * @param hash the item hash, computed with this sketch's seed + * @param value the given U value + * @throws org.apache.datasketches.common.SketchesArgumentException if the hash was computed with a different seed + */ + public void update(final ItemHash hash, final U value) { + if (hash == null) { return; } + hash.checkSeed(seed_); + insertOrIgnore(hash.h0() >>> 1, value); } void insertOrIgnore(final long hash, final U value) { diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java index 591c67f1f..bae082530 100644 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java +++ b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java @@ -26,7 +26,7 @@ import java.nio.ByteBuffer; import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.hash.MurmurHash3; +import org.apache.datasketches.hash.ItemHash; import org.apache.datasketches.tuple.Util; /** @@ -89,7 +89,7 @@ public static ArrayOfDoublesUpdatableSketch wrap(final MemorySegment seg, final * @param values The given values */ public void update(final long key, final double[] values) { - update(new long[] {key}, values); + update(ItemHash.of(key, seed_), values); } /** @@ -100,7 +100,7 @@ public void update(final long key, final double[] values) { * @param values The given values */ public void update(final double key, final double[] values) { - update(Util.doubleToLongArray(key), values); + update(ItemHash.of(key, seed_), values); } /** @@ -111,7 +111,7 @@ public void update(final double key, final double[] values) { * @param values The given values */ public void update(final String key, final double[] values) { - update(Util.stringToByteArray(key), values); + update(ItemHash.of(key, seed_), values); } /** @@ -122,8 +122,7 @@ public void update(final String key, final double[] values) { * @param values The given values */ public void update(final byte[] key, final double[] values) { - if (key == null || key.length == 0) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); + update(ItemHash.of(key, seed_), values); } /** @@ -134,8 +133,7 @@ public void update(final byte[] key, final double[] values) { * @param values The given values */ public void update(final ByteBuffer key, final double[] values) { - if (key == null || key.hasRemaining() == false) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); + update(ItemHash.of(key, seed_), values); } /** @@ -146,8 +144,7 @@ public void update(final ByteBuffer key, final double[] values) { * @param values The given values */ public void update(final int[] key, final double[] values) { - if (key == null || key.length == 0) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); + update(ItemHash.of(key, seed_), values); } /** @@ -158,8 +155,21 @@ public void update(final int[] key, final double[] values) { * @param values The given values */ public void update(final long[] key, final double[] values) { - if (key == null || key.length == 0) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); + update(ItemHash.of(key, seed_), values); + } + + /** + * Present this sketch with a precomputed item hash, as if updating with the item itself. + * A null hash is ignored. + * + * @param hash the item hash, computed with this sketch's seed + * @param values the given values + * @throws org.apache.datasketches.common.SketchesArgumentException if the hash was computed with a different seed + */ + public void update(final ItemHash hash, final double[] values) { + if (hash == null) { return; } + hash.checkSeed(seed_); + insertOrIgnore(hash.h0() >>> 1, values); } /** diff --git a/src/test/java/org/apache/datasketches/hash/ItemHashTest.java b/src/test/java/org/apache/datasketches/hash/ItemHashTest.java new file mode 100644 index 000000000..d66192370 --- /dev/null +++ b/src/test/java/org/apache/datasketches/hash/ItemHashTest.java @@ -0,0 +1,193 @@ +/* + * 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.datasketches.hash; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertThrows; + +import java.lang.foreign.MemorySegment; +import java.nio.ByteBuffer; +import java.util.function.Consumer; + +import org.apache.datasketches.common.SketchesArgumentException; +import org.apache.datasketches.common.Util; +import org.apache.datasketches.cpc.CpcSketch; +import org.apache.datasketches.hll.HllSketch; +import org.apache.datasketches.theta.UpdatableThetaSketch; +import org.apache.datasketches.theta.UpdateReturnState; +import org.apache.datasketches.tuple.UpdatableTupleSketch; +import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; +import org.apache.datasketches.tuple.adouble.DoubleSummary; +import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; +import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; +import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; +import org.testng.annotations.Test; + +public class ItemHashTest { + private static final long SEED = 12345L; + private static final int N = 20_000; + + @Test + public void singleLongMatchesOneElementArray() { + final long[] samples = {0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE, 0x0123_4567_89ab_cdefL}; + for (final long x : samples) { + assertEquals(MurmurHash3.hash(x, SEED), MurmurHash3.hash(new long[] {x}, SEED)); + } + } + + @Test + public void canonicalizesDoublesAndSkipsEmptyItems() { + assertEquals(ItemHash.of(-0.0, SEED).h0(), ItemHash.of(0.0, SEED).h0()); + assertEquals(ItemHash.of(Double.longBitsToDouble(0x7ff8_0000_0000_0001L), SEED).h0(), ItemHash.of(Double.NaN, SEED).h0()); + assertNull(ItemHash.of((String) null, SEED)); + assertNull(ItemHash.of("", SEED)); + assertNull(ItemHash.of(new byte[0], SEED)); + assertNull(ItemHash.of(new char[0], SEED)); + assertNull(ItemHash.of(new int[0], SEED)); + assertNull(ItemHash.of(new long[0], SEED)); + assertNull(ItemHash.of(ByteBuffer.allocate(0), SEED)); + assertNull(ItemHash.of(MemorySegment.ofArray(new byte[0]), SEED)); + assertEquals(ItemHash.of(MemorySegment.ofArray("abc".getBytes(UTF_8)), SEED).h0(), ItemHash.of("abc", SEED).h0()); + } + + @Test + public void thetaMatchesItemUpdates() { + final UpdatableThetaSketch byItem = UpdatableThetaSketch.builder().setNominalEntries(1024).setSeed(SEED).build(); + final UpdatableThetaSketch byHash = UpdatableThetaSketch.builder().setNominalEntries(1024).setSeed(SEED).build(); + feed(byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, + byItem::update); + feedHashes(SEED, byHash::update); + assertEquals(byHash.compact().toByteArray(), byItem.compact().toByteArray()); + assertEquals(byHash.update((ItemHash) null), UpdateReturnState.RejectedNullOrEmpty); + } + + @Test + public void tupleMatchesItemUpdates() { + final UpdatableTupleSketchBuilder builder = + new UpdatableTupleSketchBuilder(new DoubleSummaryFactory(DoubleSummary.Mode.Sum)) + .setNominalEntries(1024).setSeed(SEED); + final UpdatableTupleSketch byItem = builder.build(); + final UpdatableTupleSketch byHash = builder.build(); + feed(v -> byItem.update(v, 1.0), v -> byItem.update(v, 1.0), v -> byItem.update(v, 1.0), v -> byItem.update(v, 1.0), + v -> byItem.update(v, 1.0), null, v -> byItem.update(v, 1.0), v -> byItem.update(v, 1.0)); + feedHashesNoChars(SEED, h -> byHash.update(h, 1.0)); + assertEquals(byHash.compact().toByteArray(), byItem.compact().toByteArray()); + } + + @Test + public void arrayOfDoublesMatchesItemUpdates() { + final ArrayOfDoublesUpdatableSketchBuilder builder = + new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(1024).setSeed(SEED); + final ArrayOfDoublesUpdatableSketch byItem = builder.build(); + final ArrayOfDoublesUpdatableSketch byHash = builder.build(); + final double[] one = {1.0}; + feed(v -> byItem.update(v, one), v -> byItem.update(v, one), v -> byItem.update(v, one), v -> byItem.update(v, one), + v -> byItem.update(v, one), null, v -> byItem.update(v, one), v -> byItem.update(v, one)); + feedHashesNoChars(SEED, h -> byHash.update(h, one)); + assertEquals(byHash.compact().toByteArray(), byItem.compact().toByteArray()); + } + + @Test + public void cpcMatchesItemUpdates() { + final CpcSketch byItem = new CpcSketch(11, SEED); + final CpcSketch byHash = new CpcSketch(11, SEED); + feed(byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, + byItem::update); + feedHashes(SEED, byHash::update); + assertEquals(byHash.toByteArray(), byItem.toByteArray()); + } + + @Test + public void hllMatchesItemUpdates() { + final HllSketch byItem = new HllSketch(11); + final HllSketch byHash = new HllSketch(11); + feed(byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, byItem::update, + byItem::update); + feedHashes(Util.DEFAULT_UPDATE_SEED, byHash::update); + assertEquals(byHash.toCompactByteArray(), byItem.toCompactByteArray()); + } + + @Test + public void oneHashFeedsEverySketch() { + final long seed = Util.DEFAULT_UPDATE_SEED; + final UpdatableThetaSketch theta = UpdatableThetaSketch.builder().build(); + final CpcSketch cpc = new CpcSketch(11); + final HllSketch hll = new HllSketch(11); + final UpdatableThetaSketch thetaRef = UpdatableThetaSketch.builder().build(); + final CpcSketch cpcRef = new CpcSketch(11); + final HllSketch hllRef = new HllSketch(11); + for (int i = 0; i < N; i++) { + final String id = "user-" + i; + final ItemHash h = ItemHash.of(id, seed); + theta.update(h); + cpc.update(h); + hll.update(h); + thetaRef.update(id); + cpcRef.update(id); + hllRef.update(id); + } + assertEquals(theta.compact().toByteArray(), thetaRef.compact().toByteArray()); + assertEquals(cpc.toByteArray(), cpcRef.toByteArray()); + assertEquals(hll.toCompactByteArray(), hllRef.toCompactByteArray()); + } + + @Test + public void rejectsHashFromAnotherSeed() { + final ItemHash h = ItemHash.of(1L, SEED + 1); + assertThrows(SketchesArgumentException.class, () -> UpdatableThetaSketch.builder().setSeed(SEED).build().update(h)); + assertThrows(SketchesArgumentException.class, () -> new CpcSketch(11, SEED).update(h)); + assertThrows(SketchesArgumentException.class, () -> new HllSketch(11).update(h)); + assertThrows(SketchesArgumentException.class, () -> new ArrayOfDoublesUpdatableSketchBuilder().setSeed(SEED).build() + .update(h, new double[] {1.0})); + } + + private static void feed(final Consumer longs, final Consumer doubles, final Consumer strings, + final Consumer bytes, final Consumer buffers, final Consumer chars, + final Consumer ints, final Consumer longArrays) { + for (int i = 0; i < N; i++) { + switch (i % 8) { + case 0: longs.accept((long) i); break; + case 1: doubles.accept(i % 16 == 1 ? -0.0 : i + 0.5); break; + case 2: strings.accept(i % 16 == 2 ? "" : "s" + i); break; + case 3: bytes.accept(i % 16 == 3 ? null : ("b" + i).getBytes(UTF_8)); break; + case 4: buffers.accept(ByteBuffer.wrap(("y" + i).getBytes(UTF_8))); break; + case 5: if (chars != null) { chars.accept(("c" + i).toCharArray()); } break; + case 6: ints.accept(new int[] {i, -i}); break; + default: longArrays.accept(new long[] {i, i * 31L}); break; + } + } + } + + private static void feedHashes(final long seed, final Consumer sink) { + feed(v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed)), + v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed)), + v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed)), + v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed))); + } + + private static void feedHashesNoChars(final long seed, final Consumer sink) { + feed(v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed)), + v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed)), + v -> sink.accept(ItemHash.of(v, seed)), null, + v -> sink.accept(ItemHash.of(v, seed)), v -> sink.accept(ItemHash.of(v, seed))); + } +}