;; String chomp that copies behavior from Ruby. (2.00)
(define (chomp-suffix s pat)
;; Remove (pat) from the end of string.
(let ((m (string-length pat))
(n (string-suffix-length s pat)))
(if (= m n)
(string-drop-right s n)
s)))
(define (chomp-return-or-newline s)
;; Remove one of (\r \n \r\n) from the end of string.
(chomp-suffix (chomp-suffix s "\n") "\r"))
(define (chomp-all-newlines s)
;; Remove all of (\n \r\n) from the end of string.
(let ((n (string-suffix-length s "\r\n")))
(if (zero? n)
s
(chomp-all-newlines (string-drop-right s n)))))
;; Chomp.
(define* (chomp s #:optional (pat '()))
(cond
((null? pat)
(chomp-return-or-newline s))
((string-null? pat)
(chomp-all-newlines s))
(else
(chomp-suffix s pat))))
;; Show.
(format #t "~S~%" (chomp "hello")) ;=> "hello"
(format #t "~S~%" (chomp "hello\n")) ;=> "hello"
(format #t "~S~%" (chomp "hello\r\n")) ;=> "hello"
(format #t "~S~%" (chomp "hello\n\r")) ;=> "hello\n"
(format #t "~S~%" (chomp "hello\r")) ;=> "hello"
(format #t "~S~%" (chomp "hello \n there")) ;=> "hello \n there"
(format #t "~S~%" (chomp "hello" "llo")) ;=> "he"
(format #t "~S~%" (chomp "he-lo" "llo")) ;=> "he-lo"
(format #t "~S~%" (chomp "hello\r\n\r\n\n" "")) ;=> "hello"
(format #t "~S~%" (chomp "hello\r\n\r\r\n" "")) ;=> "hello\r\n\r"