When the buffer is empty, reset b.off to the beginning of the buffer
to avoid growing unnecessarily.
R=rsc
CC=golang-dev
https://golang.org/cl/176071
diff --git a/src/pkg/bytes/buffer.go b/src/pkg/bytes/buffer.go
index 41838d4..b302b65 100644
--- a/src/pkg/bytes/buffer.go
+++ b/src/pkg/bytes/buffer.go
@@ -84,6 +84,10 @@
// value n is the length of p; err is always nil.
func (b *Buffer) Write(p []byte) (n int, err os.Error) {
m := b.Len();
+ // If buffer is empty, reset to recover space.
+ if m == 0 && b.off != 0 {
+ b.Truncate(0)
+ }
n = len(p);
if len(b.buf)+n > cap(b.buf) {
b.resize(n)
@@ -97,6 +101,10 @@
// value n is the length of s; err is always nil.
func (b *Buffer) WriteString(s string) (n int, err os.Error) {
m := b.Len();
+ // If buffer is empty, reset to recover space.
+ if m == 0 && b.off != 0 {
+ b.Truncate(0)
+ }
n = len(s);
if len(b.buf)+n > cap(b.buf) {
b.resize(n)
@@ -117,6 +125,10 @@
// Any error except os.EOF encountered during the read
// is also returned.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
+ // If buffer is empty, reset to recover space.
+ if b.off >= len(b.buf) {
+ b.Truncate(0)
+ }
for {
if cap(b.buf)-len(b.buf) < MinRead {
var newBuf []byte;
@@ -157,6 +169,8 @@
return n, e
}
}
+ // Buffer is now empty; reset.
+ b.Truncate(0);
return;
}
@@ -175,7 +189,9 @@
// otherwise it is nil.
func (b *Buffer) Read(p []byte) (n int, err os.Error) {
if b.off >= len(b.buf) {
- return 0, os.EOF
+ // Buffer is empty, reset to recover space.
+ b.Truncate(0);
+ return 0, os.EOF;
}
m := b.Len();
n = len(p);
@@ -194,7 +210,9 @@
// If no byte is available, it returns error os.EOF.
func (b *Buffer) ReadByte() (c byte, err os.Error) {
if b.off >= len(b.buf) {
- return 0, os.EOF
+ // Buffer is empty, reset to recover space.
+ b.Truncate(0);
+ return 0, os.EOF;
}
c = b.buf[b.off];
b.off++;