aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoger Peppe <rogpeppe@gmail.com>2010-12-07 14:54:15 -0500
committerRuss Cox <rsc@golang.org>2010-12-07 14:54:15 -0500
commit24a78a026d0efd181f5b645dfb4622c826d9207a (patch)
tree984fed871fce83bf7ff77e00ae163601c53d3393
parentcf6c2121979dacdb712c5ec9124043a8e6acf89e (diff)
downloadgo-24a78a026d0efd181f5b645dfb4622c826d9207a.tar.gz
go-24a78a026d0efd181f5b645dfb4622c826d9207a.zip
bufio: make Reader.Read implement io.Reader semantics
R=rsc CC=golang-dev https://golang.org/cl/3395042
-rw-r--r--src/pkg/bufio/bufio.go67
1 files changed, 34 insertions, 33 deletions
diff --git a/src/pkg/bufio/bufio.go b/src/pkg/bufio/bufio.go
index 4e9f1cf3e4..fc4127a940 100644
--- a/src/pkg/bufio/bufio.go
+++ b/src/pkg/bufio/bufio.go
@@ -128,43 +128,44 @@ func (b *Reader) Peek(n int) ([]byte, os.Error) {
// Read reads data into p.
// It returns the number of bytes read into p.
-// If nn < len(p), also returns an error explaining
-// why the read is short. At EOF, the count will be
-// zero and err will be os.EOF.
-func (b *Reader) Read(p []byte) (nn int, err os.Error) {
- nn = 0
- for len(p) > 0 {
- n := len(p)
- if b.w == b.r {
- if b.err != nil {
- return nn, b.err
- }
- if len(p) >= len(b.buf) {
- // Large read, empty buffer.
- // Read directly into p to avoid copy.
- n, b.err = b.rd.Read(p)
- if n > 0 {
- b.lastByte = int(p[n-1])
- b.lastRuneSize = -1
- }
- p = p[n:]
- nn += n
- continue
+// It calls Read at most once on the underlying Reader,
+// hence n may be less than len(p).
+// At EOF, the count will be zero and err will be os.EOF.
+func (b *Reader) Read(p []byte) (n int, err os.Error) {
+ n = len(p)
+ if n == 0 {
+ return 0, b.err
+ }
+ if b.w == b.r {
+ if b.err != nil {
+ return 0, b.err
+ }
+ if len(p) >= len(b.buf) {
+ // Large read, empty buffer.
+ // Read directly into p to avoid copy.
+ n, b.err = b.rd.Read(p)
+ if n > 0 {
+ b.lastByte = int(p[n-1])
+ b.lastRuneSize = -1
}
- b.fill()
- continue
+ p = p[n:]
+ return n, b.err
}
- if n > b.w-b.r {
- n = b.w - b.r
+ b.fill()
+ if b.w == b.r {
+ return 0, b.err
}
- copy(p[0:n], b.buf[b.r:])
- p = p[n:]
- b.r += n
- b.lastByte = int(b.buf[b.r-1])
- b.lastRuneSize = -1
- nn += n
}
- return nn, nil
+
+ if n > b.w-b.r {
+ n = b.w - b.r
+ }
+ copy(p[0:n], b.buf[b.r:])
+ p = p[n:]
+ b.r += n
+ b.lastByte = int(b.buf[b.r-1])
+ b.lastRuneSize = -1
+ return n, nil
}
// ReadByte reads and returns a single byte.