(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
(#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))))
+\f
+(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