Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions internal-api/src/main/java/datadog/trace/util/HashingUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,17 @@ public static final int addToHash(int hash, double value) {
return addToHash(hash, Double.hashCode(value));
}

public static final int addToHash(int hash, Object[] arr, int len) {
for (int i = 0; i < len; i++) {
hash = addToHash(hash, arr[i]);
}
return hash;
}

public static final int addToHash(int hash, Object[] arr) {
return addToHash(hash, arr, arr.length);
}

public static final int hash(Iterable<?> objs) {
int result = 0;
for (Object obj : objs) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,30 @@ public void hashArrayAndIterable() {
assertEquals(hashArray, hashIterable);
}

@Test
public void addToHashArrayFoldsFromSeedLikeChainedAddToHash() {
Object[] array = new Object[] {"foo", "bar", "quux"};

// Full-array overload folds every element onto the seed; from zero it matches hash(Object[]).
assertEquals(HashingUtils.hash(array), HashingUtils.addToHash(0, array));

// A non-zero seed carries through, so the result differs from the zero-seed fold.
assertNotEquals(HashingUtils.addToHash(0, array), HashingUtils.addToHash(1, array));
}

@Test
public void addToHashArrayRespectsLen() {
Object[] array = new Object[] {"foo", "bar", "quux"};

// The len override folds only the first len elements.
assertEquals(
HashingUtils.hash(new Object[] {"foo", "bar"}), HashingUtils.addToHash(0, array, 2));
assertNotEquals(HashingUtils.addToHash(0, array), HashingUtils.addToHash(0, array, 2));

// len==0 never enters the loop and returns the seed unchanged.
assertEquals(42, HashingUtils.addToHash(42, array, 0));
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
public void booleans(boolean value) {
Expand Down
Loading