Skip to content

Commit

Permalink
Escape special chars in strings
Browse files Browse the repository at this point in the history
Vincit#31
For CLJS version also JSON stringify can be used
  • Loading branch information
Ferossgp committed Oct 8, 2018
1 parent 9c6107a commit 37fe0fa
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/venia/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,22 @@
[arg]
(str "[" (apply str (interpose "," (map arg->str arg))) "]"))

(defn encode-string
"Handles escaping special characters."
[arg]
(str "\"" (str/escape arg {\" "\\\""
\\ "\\\\"
\newline "\\n"
\return "\\r"
\tab "\\t"
\formfeed "\\f"
\backspace "\\b"}) "\""))

#?(:clj (extend-protocol ArgumentFormatter
nil
(arg->str [arg] "null")
String
(arg->str [arg] (str "\"" arg "\""))
(arg->str [arg] (encode-string arg))
UUID
(arg->str [arg] (str "\"" arg "\""))
IPersistentMap
Expand All @@ -46,7 +57,7 @@
nil
(arg->str [arg] "null")
string
(arg->str [arg] (str "\"" arg "\""))
(arg->str [arg] (encode-string arg))
UUID
(arg->str [arg] (str "\"" arg "\""))
PersistentArrayMap
Expand Down
7 changes: 7 additions & 0 deletions test/venia/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
(deftest ArgumentFormatter-test
(is (= "null" (v/arg->str nil)))
(is (= "\"human\"" (v/arg->str "human")))
(is (= "\"\\\"human\\\"\"" (v/arg->str "\"human\"")))
(is (= "\"What's a \\\"human\\\"?\"" (v/arg->str "What's a \"human\"?")))
(is (= "\"hu\\nman\"" (v/arg->str (str "hu" \newline "man"))))
(is (= "\"hu\\rman\"" (v/arg->str (str "hu" \return "man"))))
(is (= "\"hu\\tman\"" (v/arg->str (str "hu" \tab "man"))))
(is (= "\"hu\\fman\"" (v/arg->str (str "hu" \formfeed "man"))))
(is (= "\"hu\\bman\"" (v/arg->str (str "hu" \backspace "man"))))
(is (= "{id:1}" (v/arg->str {:id 1})))
(is (= "{id:null}" (v/arg->str {:id nil})))
(is (= "[1,2,3]" (v/arg->str [1 2 3])))
Expand Down

0 comments on commit 37fe0fa

Please sign in to comment.