Skip to content

Commit d7175e8

Browse files
jafingerhutstuarthalloway
authored andcommitted
Change clojure.string/trim so it uses same defn of whitespace as other trim fns
Signed-off-by: Stuart Halloway <[email protected]>
1 parent 17b1835 commit d7175e8

File tree

2 files changed

+27
-12
lines changed

2 files changed

+27
-12
lines changed

src/clj/clojure/string.clj

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -233,18 +233,30 @@ Design notes for clojure.string:
233233
"Removes whitespace from both ends of string."
234234
{:added "1.2"}
235235
[^CharSequence s]
236-
(.. s toString trim))
236+
(let [len (.length s)]
237+
(loop [rindex len]
238+
(if (zero? rindex)
239+
""
240+
(if (Character/isWhitespace (.charAt s (dec rindex)))
241+
(recur (dec rindex))
242+
;; there is at least one non-whitespace char in the string,
243+
;; so no need to check for lindex reaching len.
244+
(loop [lindex 0]
245+
(if (Character/isWhitespace (.charAt s lindex))
246+
(recur (inc lindex))
247+
(.. s (subSequence lindex rindex) toString))))))))
237248

238249
(defn ^String triml
239250
"Removes whitespace from the left side of string."
240251
{:added "1.2"}
241252
[^CharSequence s]
242-
(loop [index (int 0)]
243-
(if (= (.length s) index)
244-
""
245-
(if (Character/isWhitespace (.charAt s index))
246-
(recur (inc index))
247-
(.. s (subSequence index (.length s)) toString)))))
253+
(let [len (.length s)]
254+
(loop [index 0]
255+
(if (= len index)
256+
""
257+
(if (Character/isWhitespace (.charAt s index))
258+
(recur (unchecked-inc index))
259+
(.. s (subSequence index len) toString))))))
248260

249261
(defn ^String trimr
250262
"Removes whitespace from the right side of string."
@@ -253,8 +265,8 @@ Design notes for clojure.string:
253265
(loop [index (.length s)]
254266
(if (zero? index)
255267
""
256-
(if (Character/isWhitespace (.charAt s (dec index)))
257-
(recur (dec index))
268+
(if (Character/isWhitespace (.charAt s (unchecked-dec index)))
269+
(recur (unchecked-dec index))
258270
(.. s (subSequence 0 index) toString)))))
259271

260272
(defn ^String trim-newline

test/clojure/test_clojure/string.clj

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,17 @@
6767

6868
(deftest t-triml
6969
(is (= "foo " (s/triml " foo ")))
70-
(is (= "" (s/triml " "))))
70+
(is (= "" (s/triml " ")))
71+
(is (= "bar" (s/triml "\u2002 \tbar"))))
7172

7273
(deftest t-trimr
7374
(is (= " foo" (s/trimr " foo ")))
74-
(is (= "" (s/trimr " "))))
75+
(is (= "" (s/trimr " ")))
76+
(is (= "bar" (s/trimr "bar\t \u2002"))))
7577

7678
(deftest t-trim
77-
(is (= "foo" (s/trim " foo \r\n"))))
79+
(is (= "foo" (s/trim " foo \r\n")))
80+
(is (= "bar" (s/trim "\u2000bar\t \u2002"))))
7881

7982
(deftest t-upper-case
8083
(is (= "FOOBAR" (s/upper-case "Foobar"))))

0 commit comments

Comments
 (0)