Fix computation of hash codes for Listing, Duration, DataSize (#1922)

These are currently breaking the principle of: if two objects are
`equals`, then they have the same hash code.
This commit is contained in:
Daniel Chao authored and GitHub committed 2026-10-30 10:31:06 -07:00
1 parent 0b582b50b4
commit b1b36b09ac
5 files changed
+58 -12

No files matched your search

@@ -152,7 +152,8 @@ public final class VmDataSize extends VmValue implements Comparable<VmDataSize>
@Override
public int hashCode() {
return Double.hashCode(convertValueTo(DataSizeUnit.BYTES));
// adding 0.0 normalizes -0.0 to 0.0, because -0.0 == 0.0 but their hash codes differ
return Double.hashCode(convertValueTo(DataSizeUnit.BYTES) + 0.0);
}
@Override
@@ -149,7 +149,8 @@ public final class VmDuration extends VmValue implements Comparable<VmDuration>
@Override
public int hashCode() {
return Double.hashCode(getValue(DurationUnit.NANOS));
// adding 0.0 normalizes -0.0 to 0.0, because -0.0 == 0.0 but their hash codes differ
return Double.hashCode(getValue(DurationUnit.NANOS) + 0.0);
}
@Override
@@ -212,18 +212,10 @@ public final class VmListing extends VmListingOrMapping {
force(false);
var result = 0;
var cursor = cachedValues.getEntries();
while (cursor.advance()) {
var key = cursor.getKey();
if (key instanceof Identifier) continue;
var value = cursor.getValue();
//noinspection ConstantValue
assert value != null;
for (var cursor = elements(); cursor.advance(); ) {
var value = cursor.cachedValue();
result = 31 * result + value.hashCode();
}
cachedHash = result;
return result;
}
@@ -0,0 +1,38 @@
local l1: Listing = new {
new { x = 1 }
new { x = 2 }
}
local l2: Listing = new {
new { x = 1 }
new { x = 2 }
}
local m1: Mapping = new {
["a"] { x = 1 }
["b"] { x = 2 }
}
local m2: Mapping = new {
["a"] { x = 1 }
["b"] { x = 2 }
}
res1 {
first = l2[1]
// https://github.com/apple/pkl/issues/1920
size = Set(l1, l2).length
}
res2 {
first = m2["b"]
size = Set(m1, m2).length
}
local bigList = IntSeq(1, 200).toList().map((i) -> i.b)
// https://github.com/apple/pkl/issues/1921
res3 = (bigList + List(0.b, -0.b)).toSet().length - bigList.length
// https://github.com/apple/pkl/issues/1921
res4 = (bigList + List(0.ms, -0.ms)).toSet().length - bigList.length
@@ -0,0 +1,14 @@
res1 {
first {
x = 2
}
size = 1
}
res2 {
first {
x = 2
}
size = 1
}
res3 = 1
res4 = 1