From eefca53fd9f6fdb2b5c8df054a73a5b0cb0b8d2f Mon Sep 17 00:00:00 2001 From: Matt Birkholz Date: Thu, 2 Nov 2017 09:00:09 -0700 Subject: [PATCH] ustring (string-trim): Handle strings trimmed to nothing. Also added tests for string-trim. Thanks to Peter . --- src/runtime/ustring.scm | 34 +++++++++++++++++----------------- tests/runtime/test-string.scm | 17 ++++++++++++++++- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/src/runtime/ustring.scm b/src/runtime/ustring.scm index 2cada76b3..dd7394479 100644 --- a/src/runtime/ustring.scm +++ b/src/runtime/ustring.scm @@ -1962,23 +1962,23 @@ USA. (let ((predicate (char-matcher->predicate to-trim 'string-trimmer)) (get-trimmed (if copy? substring string-slice))) (lambda (string) - (let ((end (string-length string))) - (get-trimmed - string - (if (eq? where 'trailing) - 0 - (let loop ((index 0)) - (if (and (fix:< index end) - (predicate (string-ref string index))) - (loop (fix:+ index 1)) - index))) - (if (eq? where 'leading) - end - (let loop ((index end)) - (if (and (fix:> index 0) - (predicate (string-ref string (fix:- index 1)))) - (loop (fix:- index 1)) - index))))))))) + (let* ((end (string-length string)) + (start (if (eq? where 'trailing) + 0 + (let loop ((index 0)) + (if (and (fix:< index end) + (predicate (string-ref string index))) + (loop (fix:+ index 1)) + index)))) + (end (if (eq? where 'leading) + end + (let loop ((index end)) + (if (and (fix:> index 0) + (predicate + (string-ref string (fix:- index 1)))) + (loop (fix:- index 1)) + index))))) + (get-trimmed string (min start end) end)))))) (define-deferred string-trimmer-options (keyword-option-parser diff --git a/tests/runtime/test-string.scm b/tests/runtime/test-string.scm index 44f37966a..0291229d2 100644 --- a/tests/runtime/test-string.scm +++ b/tests/runtime/test-string.scm @@ -3075,4 +3075,19 @@ USA. (#t #\x0061 #f #\x005F #f #\x0061 #t #\x002C #t #\x002C #t #\x0031 #t) (#t #\x0061 #t #\x002C #t #\x002C #t #\x0061 #t) (#t #\x0061 #f #\x005F #f #\x0031 #t #\x002C #t #\x002C #t #\x0061 #t) - (#t #\x0061 #f #\x005F #f #\x0061 #t #\x002C #t #\x002C #t #\x0061 #t)))) \ No newline at end of file + (#t #\x0061 #f #\x005F #f #\x0061 #t #\x002C #t #\x002C #t #\x0061 #t)))) + +(define-test 'string-trim + (lambda () + (define-integrable = assert-string=) + (= "foo" (string-trim "foo ")) + (= "foo" (string-trim " foo")) + (= "foo" (string-trim " foo ")) + (= "foo " (string-trim-left " foo ")) + (= " foo" (string-trim-right " foo ")) + (= "" (string-trim "\"\"" (char-set-invert (char-set #\")))) + (= "" (string-trim-left "\"\"" (char-set-invert (char-set #\")))) + (= "" (string-trim-right "\"\"" (char-set-invert (char-set #\")))) + (= "foo" (string-trim "aaafooaaa" (char-set #\f #\o))) + (= "fooaaa" (string-trim-left "aaafooaaa" (char-set #\f #\o))) + (= "aaafoo" (string-trim-right "aaafooaaa" (char-set #\f #\o))))) \ No newline at end of file -- 2.25.1