Skip to content

Commit 4cec93a

Browse files
committed
simplify code for handling float 0/-0
1 parent ccb2a4c commit 4cec93a

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

lib/pure/hashes.nim

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,11 @@ proc hash*[T: SomeNumber | Ordinal | char](x: T): Hash {.inline.} =
118118
# bugfix: the previous code was using `x = x + 1.0` (presumably for
119119
# handling negative 0), however this leads to collisions for small x due
120120
# to FP finite precision.
121-
let x: BiggestInt =
122-
if x == 0: 0.BiggestInt
123-
else:
124-
when sizeof(BiggestInt) == sizeof(T):
125-
cast[BiggestInt](x)
126-
else: # for nimvm
127-
cast[int32](x).BiggestInt
121+
let x = block:
122+
when sizeof(BiggestInt) == sizeof(T):
123+
cast[BiggestInt](x + T(0))
124+
else: # for nimvm
125+
cast[int32](x + T(0)).BiggestInt
128126
else:
129127
let x = x.BiggestInt
130128
hashBiggestInt(x)

tests/stdlib/thashes.nim

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,10 @@ suite "hashes":
1515
test "0.0 and -0.0 should have the same hash value":
1616
var dummy = 0.0
1717
check hash(dummy) == hash(-dummy)
18+
check hash(0.0) == hash(-0.0)
19+
check hash(0.0f) == hash(-0.0f)
20+
let h1 = hash(0.0)
21+
const h2 = hash(0.0)
22+
const h3 = hash(-0.0)
23+
check h1 == h2
24+
check h1 == h3

0 commit comments

Comments
 (0)