Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CLJS-3410: JavaScript double values should not hash to the same result #220

Merged
merged 4 commits into from
Jan 22, 2024
Merged
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
14 changes: 13 additions & 1 deletion src/main/cljs/cljs/core.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,16 @@
h1 (m3-mix-H1 m3-seed k1)]
(m3-fmix h1 4))))

(defn hash-long [high low]
(bit-xor high low))

(defn hash-double [f]
(let [arr (doto (js/Float64Array. 1) (aset 0 f))
buf (.-buffer arr)
high (.getInt32 (js/DataView. buf 0 4))
low (.getInt32 (js/DataView. buf 4 4))]
(hash-long high low)))

(defn ^number m3-hash-unencoded-chars [in]
(let [h1 (loop [i 1 h1 m3-seed]
(if (< i (.-length in))
Expand Down Expand Up @@ -1021,7 +1031,9 @@

(number? o)
(if ^boolean (js/isFinite o)
(js-mod (Math/floor o) 2147483647)
(if-not ^boolean (.isSafeInteger js/Number o)
(hash-double o)
(js-mod (Math/floor o) 2147483647))
(case o
##Inf
2146435072
Expand Down
9 changes: 9 additions & 0 deletions src/test/cljs/cljs/hashing_test.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,12 @@
(deftest test-cljs-1818
(is (= (hash true) 1231))
(is (= (hash false) 1237)))

(deftest test-cljs-3410
(testing "Small doubles should not hash the same"
(is (not= (hash-double -0.32553251) (hash-double -0.0000032553251)))
(is (not= (hash -0.32553251) (hash -0.0000032553251))))
(testing "Same double hashes the same"
(is (= (hash 0.5) (hash 0.5)))
(is (= (hash -0.32553251) (hash -0.32553251)))
(is (= (hash -0.0000032553251) (hash -0.0000032553251)))))
Loading