Skip to content

Commit

Permalink
string perf tweaks, tests #359
Browse files Browse the repository at this point in the history
Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
  • Loading branch information
David Liebke and Stuart Halloway authored and stuarthalloway committed Jun 4, 2010
1 parent 07fc530 commit b7f2113
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 14 deletions.
28 changes: 19 additions & 9 deletions src/clj/clojure/string.clj
Expand Up @@ -67,7 +67,7 @@
(if (string? replacement)
(.replaceFirst (re-matcher ^Pattern match s) ^String replacement)
(replace-first-by s match replacement))
:default (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
:else (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))


(defn ^String join
Expand Down Expand Up @@ -118,23 +118,33 @@
(defn ^String triml
"Removes whitespace from the left side of string."
[^String s]
(replace s #"^\s+" ""))
(loop [index (int 0)]
(if (= (.length s) index)
""
(if (Character/isWhitespace (.charAt s index))
(recur (inc index))
(.substring s index)))))

(defn ^String trimr
"Removes whitespace from the right side of string."
[^String s]
(replace s #"\s+$" ""))
(loop [index (.length s)]
(if (zero? index)
""
(if (Character/isWhitespace (.charAt s (dec index)))
(recur (dec index))
(.substring s 0 index)))))

(defn ^String trim-nl
(defn ^String trim-newline
"Removes all trailing newline \\n or return \\r characters from
string. Note: String.trim() is similar and faster."
[^String s]
(loop [offset (.length s)]
(if (zero? offset)
(loop [index (.length s)]
(if (zero? index)
""
(let [ch (.charAt s (dec offset))]
(let [ch (.charAt s (dec index))]
(if (or (= ch \newline) (= ch \return))
(recur (dec offset))
(.substring s 0 offset))))))
(recur (dec index))
(.substring s 0 index))))))


5 changes: 5 additions & 0 deletions test/clojure/test_clojure.clj
Expand Up @@ -58,6 +58,11 @@
:rt
:repl
:java.io
:string
:java.javadoc
:java.shell
:transients
:def
])

(def test-namespaces
Expand Down
10 changes: 5 additions & 5 deletions test/clojure/test_clojure/string.clj
Expand Up @@ -27,11 +27,11 @@
"1" \, [1]
"1 and-a 2 and-a 3" " and-a " [1 2 3]))

(deftest t-trim-nl
(is (= "foo" (s/trim-nl "foo\n")))
(is (= "foo" (s/trim-nl "foo\r\n")))
(is (= "foo" (s/trim-nl "foo")))
(is (= "" (s/trim-nl ""))))
(deftest t-trim-newline
(is (= "foo" (s/trim-newline "foo\n")))
(is (= "foo" (s/trim-newline "foo\r\n")))
(is (= "foo" (s/trim-newline "foo")))
(is (= "" (s/trim-newline ""))))

(deftest t-capitalize
(is (= "Foobar" (s/capitalize "foobar")))
Expand Down

0 comments on commit b7f2113

Please sign in to comment.