Skip to content

Commit

Permalink
Fixes read-handlers with multiple arities (closes cognitect#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
tonsky committed Oct 21, 2024
1 parent 3d8a2c4 commit 4bcf345
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 15 deletions.
32 changes: 17 additions & 15 deletions src/cognitect/transit.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -115,21 +115,23 @@
(t/reader (name type)
(opts-merge
#js {:handlers
(clj->js
(merge
{"$" (fn [v] (symbol v))
":" (fn [v] (keyword v))
"set" (fn [v] (into #{} v))
"list" (fn [v] (into () (.reverse v)))
"cmap" (fn [v]
(loop [i 0 ret (transient {})]
(if (< i (alength v))
(recur (+ i 2)
(assoc! ret (aget v i) (aget v (inc i))))
(persistent! ret))))
"with-meta"
(fn [v] (with-meta (aget v 0) (aget v 1)))}
(dissoc (:handlers opts) :default)))
(reduce-kv
(fn [m tag handler]
(gobj/set m (clj->js tag) #(handler %))
m)
#js {"$" (fn [v] (symbol v))
":" (fn [v] (keyword v))
"set" (fn [v] (into #{} v))
"list" (fn [v] (into () (.reverse v)))
"cmap" (fn [v]
(loop [i 0 ret (transient {})]
(if (< i (alength v))
(recur (+ i 2)
(assoc! ret (aget v i) (aget v (inc i))))
(persistent! ret))))
"with-meta"
(fn [v] (with-meta (aget v 0) (aget v 1)))}
(dissoc (:handlers opts) :default))
:defaultHandler (-> opts :handlers :default)
:mapBuilder (MapBuilder.)
:arrayBuilder (VectorBuilder.)
Expand Down
30 changes: 30 additions & 0 deletions test/transit/test/core.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,36 @@
(is (= (t/read cr "[\"~:foo\", 1]")
[:foo 1])))

(deftest test-read-custom-arities
(is (= (t/read (t/reader :json
{:handlers
{"custom" (fn [x]
x)}})
"[\"~#custom\",\"abc\"]")
"abc"))
(is (= (t/read (t/reader :json
{:handlers
{"custom" (fn
([] nil)
([x] x))}})
"[\"~#custom\",\"abc\"]")
"abc"))
(is (= (t/read (t/reader :json
{:handlers
{"custom" (fn
([x] x)
([x y] [x y]))}})
"[\"~#custom\",\"abc\"]")
"abc"))
(is (= (t/read (t/reader :json
{:handlers
{"custom" (fn
([] nil)
([x] x)
([x y] [x y]))}})
"[\"~#custom\",\"abc\"]")
"abc")))

(def cw
(t/writer :json
{:handlers
Expand Down

0 comments on commit 4bcf345

Please sign in to comment.