From ebcc37560cb6dd2306b4deb47a8b17a46b2fff7c Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Tue, 25 Jan 2011 09:20:41 -0800 Subject: [PATCH] Make encoding/line an io.Reader Already submitted to Go at http://codereview.appspot.com/4066043/ --- lib/go/line/line.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/go/line/line.go b/lib/go/line/line.go index 92dddcb99..ca4e8cd4d 100644 --- a/lib/go/line/line.go +++ b/lib/go/line/line.go @@ -28,6 +28,27 @@ func NewReader(in io.Reader, maxLineLength int) *Reader { } } +// Read reads from any buffered data past the last line read, or from the underlying +// io.Reader if the buffer is empty. +func (l *Reader) Read(p []byte) (n int, err os.Error) { + l.removeConsumedFromBuffer() + if len(l.buf) > 0 { + n = copy(p, l.buf) + err = nil + l.consumed += n + return + } + return l.in.Read(p) +} + +func (l *Reader) removeConsumedFromBuffer() { + if l.consumed > 0 { + n := copy(l.buf, l.buf[l.consumed:]) + l.buf = l.buf[:n] + l.consumed = 0 + } +} + // ReadLine tries to return a single line, not including the end-of-line bytes. // If the line was found to be longer than the maximum length then isPrefix is // set and the beginning of the line is returned. The rest of the line will be @@ -36,11 +57,7 @@ func NewReader(in io.Reader, maxLineLength int) *Reader { // the Reader and is only valid until the next call to ReadLine. ReadLine // either returns a non-nil line or it returns an error, never both. func (l *Reader) ReadLine() (line []byte, isPrefix bool, err os.Error) { - if l.consumed > 0 { - n := copy(l.buf, l.buf[l.consumed:]) - l.buf = l.buf[:n] - l.consumed = 0 - } + l.removeConsumedFromBuffer() if len(l.buf) == 0 && l.err != nil { err = l.err