Skip to content

Commit

Permalink
optimized header parse fns; throw on nil input
Browse files Browse the repository at this point in the history
  • Loading branch information
onionpancakes committed Oct 14, 2023
1 parent b4ade90 commit e33f4c5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
10 changes: 6 additions & 4 deletions src/dev/onionpancakes/hop/headers.clj
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@
(defn parse-media-type
"Parse the mimetype from a content-type string. Truncates all whitespace."
[s]
(when-let [parse (and s (re-find parse-media-type-regex s))]
(str (second parse) "/" (nth parse 2))))
(let [m (re-matcher parse-media-type-regex s)]
(when (.find m)
(str (.group m 1) "/" (.group m 2)))))

(def parse-media-type-function
(reify java.util.function.Function
Expand All @@ -39,8 +40,9 @@
(defn parse-character-encoding
"Parse the character encoding from a content-type string."
[s]
(when s
(second (re-find parse-character-encoding-regex s))))
(let [m (re-matcher parse-character-encoding-regex s)]
(when (.find m)
(.group m 1))))

(def parse-character-encoding-function
(reify java.util.function.Function
Expand Down
18 changes: 9 additions & 9 deletions test/dev/onionpancakes/hop/test_headers.clj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

(deftest test-parse-media-type
(are [s expected] (= (h/parse-media-type s) expected)
nil nil
"" nil
"text" nil
"texthtml" nil
Expand All @@ -13,14 +12,15 @@
"text/html" "text/html"
"text/html " "text/html"
"text/html;" "text/html"
"text / html ;" "text/html"))
"text / html ;" "text/html"
"text/html+foo" "text/html+foo"))

(deftest test-parse-character-encoding
(are [s expected] (= (h/parse-character-encoding s) expected)
nil nil
"" nil
"charset=" nil
"charset=utf-8" "utf-8"
"text/html; charset=utf-8" "utf-8"
"text/html; charset = utf-8" "utf-8"
"text/html; charset=UTF-8" "UTF-8"))
"" nil
"charset=" nil
"charset=utf-8" "utf-8"
"text/html; charset=utf-8" "utf-8"
"text/html; charset = utf-8" "utf-8"
"text/html; charset=UTF-8" "UTF-8"
"text/html+foo; charset=UTF-8" "UTF-8"))

0 comments on commit e33f4c5

Please sign in to comment.