Skip to content

Commit

Permalink
Add native implementation for IKVReduce in toucan2.instance.Instance (#…
Browse files Browse the repository at this point in the history
…174)

Without this, if kv-reduce is called on an Instance, the code follows the slow
unoptimal path of calling 'reduce' on the map and constructing MapEntries.
  • Loading branch information
alexander-yakushev authored Aug 26, 2024
1 parent 308cf94 commit 4dfb559
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/toucan2/instance.clj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
current value and their model is the same."
(:refer-clojure :exclude [instance?])
(:require
clojure.core.protocols
[potemkin :as p]
[pretty.core :as pretty]
[toucan2.protocols :as protocols]
Expand Down Expand Up @@ -137,6 +138,10 @@
(asTransient [_this]
(->TransientInstance model (transient m) mta))

clojure.lang.IKVReduce
(kvreduce [_this f init]
(clojure.core.protocols/kv-reduce m f init))

protocols/IModel
(protocols/model [_this]
model)
Expand Down
5 changes: 5 additions & 0 deletions test/toucan2/instance_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,8 @@
m2 (assoc m :location nil)]
(is (= {:location nil}
(protocols/changes m2))))))

(deftest ^:parallel reduce-kv-test
(testing "instance supports IKVReduce iteration natively"
(let [instance (instance/instance ::foo (zipmap (range 100) (range)))]
(is (= 100 (.kvreduce instance (fn [c _ _] (inc c)) 0))))))

0 comments on commit 4dfb559

Please sign in to comment.