1
0
mirror of https://github.com/golang/go synced 2024-11-25 08:57:58 -07:00

bytes: simplified logic

Also: Avoid potential crash due to reslicing of nil buffer.

R=r
CC=golang-dev
https://golang.org/cl/5556075
This commit is contained in:
Robert Griesemer 2012-01-20 15:39:14 -08:00
parent 531ded922f
commit 35ba05ee28

View File

@ -139,21 +139,19 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
b.Truncate(0) b.Truncate(0)
} }
for { for {
if cap(b.buf)-len(b.buf) < MinRead { if free := cap(b.buf) - len(b.buf); free < MinRead {
var newBuf []byte // not enough space at end
// can we get space without allocation? newBuf := b.buf
if b.off+cap(b.buf)-len(b.buf) >= MinRead { if b.off+free < MinRead {
// reuse beginning of buffer // not enough space using beginning of buffer;
newBuf = b.buf[0 : len(b.buf)-b.off] // double buffer capacity
} else { newBuf = makeSlice(2*cap(b.buf) + MinRead)
// not enough space at end; put space on end
newBuf = makeSlice(2*(cap(b.buf)-b.off) + MinRead)[:len(b.buf)-b.off]
if newBuf == nil { if newBuf == nil {
return n, ErrTooLarge return n, ErrTooLarge
} }
} }
copy(newBuf, b.buf[b.off:]) copy(newBuf, b.buf[b.off:])
b.buf = newBuf b.buf = newBuf[:len(b.buf)-b.off]
b.off = 0 b.off = 0
} }
m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]) m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])