]> git.kaiwu.me - quickjs.git/commitdiff
Fix Map hash bug
authorCharlie Gordon <github@chqrlie.org>
Thu, 22 Feb 2024 18:31:57 +0000 (19:31 +0100)
committerCharlie Gordon <github@chqrlie.org>
Thu, 22 Feb 2024 18:31:57 +0000 (19:31 +0100)
- `map_hash_key` must generate the same key for JS_INT and JS_FLOAT64
   with the same value
- add test cases in tests/test_builtin.js

quickjs.c
tests/test_builtin.js

index 9024aa82690d744e680e2892953f47c7e8b0b481..c660b2d60d3da58e52cc9152f497ef439379f830 100644 (file)
--- a/quickjs.c
+++ b/quickjs.c
@@ -46963,7 +46963,7 @@ static uint32_t map_hash_key(JSContext *ctx, JSValueConst key)
         h = (uintptr_t)JS_VALUE_GET_PTR(key) * 3163;
         break;
     case JS_TAG_INT:
-        d = JS_VALUE_GET_INT(key) * 3163;
+        d = JS_VALUE_GET_INT(key);
         goto hash_float64;
     case JS_TAG_FLOAT64:
         d = JS_VALUE_GET_FLOAT64(key);
@@ -46973,7 +46973,7 @@ static uint32_t map_hash_key(JSContext *ctx, JSValueConst key)
     hash_float64:
         u.d = d;
         h = (u.u32[0] ^ u.u32[1]) * 3163;
-        break;
+        return h ^= JS_TAG_FLOAT64;
     default:
         h = 0; /* XXX: bignum support */
         break;
index f4fece8373ec611a09d19e78c318386f5a3682c8..22c546428a20ef54ec619d94b9c2fda60bd758cf 100644 (file)
@@ -671,6 +671,20 @@ function test_map()
 {
     var a, i, n, tab, o, v;
     n = 1000;
+
+    a = new Map();
+    for (var i = 0; i < n; i++) {
+        a.set(i, i);
+    }
+    a.set(-2147483648, 1);
+    assert(a.get(-2147483648), 1);
+    assert(a.get(-2147483647 - 1), 1);
+    assert(a.get(-2147483647.5 - 0.5), 1);
+
+    a.set(1n, 1n);
+    assert(a.get(1n), 1n);
+    assert(a.get(2n**1000n - (2n**1000n - 1n)), 1n);
+
     a = new Map();
     tab = [];
     for(i = 0; i < n; i++) {