diff --git a/lib/chibi/io/io.scm b/lib/chibi/io/io.scm index ce7f58bf..5ccdd4bc 100644 --- a/lib/chibi/io/io.scm +++ b/lib/chibi/io/io.scm @@ -71,23 +71,25 @@ ((not string-streams) (define (%read-line n in) (let ((out (open-output-string))) - (let lp () - (let ((ch (read-char in))) + (let lp ((i 0)) + (let ((ch (peek-char in))) (cond ((eof-object? ch) (let ((res (get-output-string out))) (and (not (equal? res "")) res))) + ((eqv? ch #\newline) + (read-char in) + (get-output-string out)) + ((eqv? ch #\return) + (read-char in) + (if (eqv? #\newline (peek-char in)) + (read-char in)) + (get-output-string out)) + ((>= i n) + (get-output-string out)) (else - (write-char ch out) - (cond - ((eqv? ch #\newline) - (get-output-string out)) - ((eqv? ch #\return) - (if (eqv? #\newline (peek-char in)) - (read-char in)) - (get-output-string out)) - (else - (lp))))))))))) + (write-char (read-char in) out) + (lp (+ i 1)))))))))) (define (read-line . o) (let ((in (if (pair? o) (car o) (current-input-port))) diff --git a/tests/io-tests.scm b/tests/io-tests.scm index d434d31a..289362a3 100644 --- a/tests/io-tests.scm +++ b/tests/io-tests.scm @@ -19,6 +19,13 @@ (call-with-input-string "abc\ndef\n" (lambda (in) (let ((line (read-line in))) (list line (read-line in)))))) +(test "read-line" '("abc" "def" "ghi") + (call-with-input-string "abcdef\nghi\n" + (lambda (in) + (let* ((line1 (read-line in 3)) + (line2 (read-line in 3))) + (list line1 line2 (read-line in 3)))))) + (test "read-line-to-eof" '("abc" "def") (call-with-input-string "abc\ndef" (lambda (in) (let ((line (read-line in))) (list line (read-line in))))))