Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

clojure.lang.APersistentMap-like hashing for maps

Introduces a new function -- cljs.core/hash-imap -- which calculates a
hash for an IMap using the algorithm from c.l.APM, which is
independent of the ordering on map entries.

This is necessary so that the various map types hash to the same value
when equal, independent of insertion ordering and the like and without
sorting of keys.
  • Loading branch information...
commit 6fd16df50bca7a6118693712e6918c70a64de255 1 parent 0b7d04b
Michał Marczyk authored April 21, 2012 David Nolen committed April 21, 2012

Showing 1 changed file with 13 additions and 3 deletions. Show diff stats Hide diff stats

  1. 16  src/cljs/cljs/core.cljs
16  src/cljs/cljs/core.cljs
@@ -1177,6 +1177,16 @@ reduces them without incurring seq initialization"
1177 1177
 (defn- hash-coll [coll]
1178 1178
   (reduce #(hash-combine %1 (hash %2)) (hash (first coll)) (next coll)))
1179 1179
 
  1180
+(defn- hash-imap [m]
  1181
+  ;; a la clojure.lang.APersistentMap
  1182
+  (loop [h 0 s (seq m)]
  1183
+    (if s
  1184
+      (let [e (first s)]
  1185
+        (recur (mod (+ h (bit-xor (hash (key e)) (hash (val e))))
  1186
+                    4503599627370496)
  1187
+               (next s)))
  1188
+      h)))
  1189
+
1180 1190
 (declare name)
1181 1191
 
1182 1192
 (defn- extend-object!
@@ -2588,7 +2598,7 @@ reduces them without incurring seq initialization"
2588 2598
   (-equiv [coll other] (equiv-map coll other))
2589 2599
 
2590 2600
   IHash
2591  
-  (-hash [coll] (hash-coll coll))
  2601
+  (-hash [coll] (hash-imap coll))
2592 2602
 
2593 2603
   ISeqable
2594 2604
   (-seq [coll]
@@ -2675,7 +2685,7 @@ reduces them without incurring seq initialization"
2675 2685
   (-equiv [coll other] (equiv-map coll other))
2676 2686
 
2677 2687
   IHash
2678  
-  (-hash [coll] (hash-coll coll))
  2688
+  (-hash [coll] (hash-imap coll))
2679 2689
 
2680 2690
   ISeqable
2681 2691
   (-seq [coll]
@@ -3105,7 +3115,7 @@ reduces them without incurring seq initialization"
3105 3115
   (-equiv [coll other] (equiv-map coll other))
3106 3116
 
3107 3117
   IHash
3108  
-  (-hash [coll] (hash-coll coll))
  3118
+  (-hash [coll] (hash-imap coll))
3109 3119
 
3110 3120
   ISeqable
3111 3121
   (-seq [coll]

0 notes on commit 6fd16df

Please sign in to comment.
Something went wrong with that request. Please try again.