1
0
mirror of https://github.com/golang/go synced 2024-11-22 01:54:42 -07:00

bufio: Write and WriteString cleanup

Write never writes less than the buffer size and WriteString takes advantage
of the copy built-in to improve write efficiency.

R=rsc, ality, rog
CC=golang-dev
https://golang.org/cl/4344060
This commit is contained in:
Evan Shaw 2011-04-04 15:57:10 -04:00 committed by Russ Cox
parent 5fd0a74987
commit 06ee80d6eb

View File

@ -415,38 +415,27 @@ func (b *Writer) Buffered() int { return b.n }
// If nn < len(p), it also returns an error explaining // If nn < len(p), it also returns an error explaining
// why the write is short. // why the write is short.
func (b *Writer) Write(p []byte) (nn int, err os.Error) { func (b *Writer) Write(p []byte) (nn int, err os.Error) {
if b.err != nil { for len(p) > b.Available() && b.err == nil {
return 0, b.err var n int
} if b.Buffered() == 0 {
nn = 0
for len(p) > 0 {
n := b.Available()
if n <= 0 {
if b.Flush(); b.err != nil {
break
}
n = b.Available()
}
if b.Buffered() == 0 && len(p) >= len(b.buf) {
// Large write, empty buffer. // Large write, empty buffer.
// Write directly from p to avoid copy. // Write directly from p to avoid copy.
n, b.err = b.wr.Write(p) n, b.err = b.wr.Write(p)
nn += n } else {
p = p[n:] n = copy(b.buf[b.n:], p)
if b.err != nil { b.n += n
break b.Flush()
}
continue
} }
if n > len(p) {
n = len(p)
}
copy(b.buf[b.n:b.n+n], p[0:n])
b.n += n
nn += n nn += n
p = p[n:] p = p[n:]
} }
return nn, b.err if b.err != nil {
return nn, b.err
}
n := copy(b.buf[b.n:], p)
b.n += n
nn += n
return nn, nil
} }
// WriteByte writes a single byte. // WriteByte writes a single byte.
@ -496,24 +485,21 @@ func (b *Writer) WriteRune(rune int) (size int, err os.Error) {
// If the count is less than len(s), it also returns an error explaining // If the count is less than len(s), it also returns an error explaining
// why the write is short. // why the write is short.
func (b *Writer) WriteString(s string) (int, os.Error) { func (b *Writer) WriteString(s string) (int, os.Error) {
nn := 0
for len(s) > b.Available() && b.err == nil {
n := copy(b.buf[b.n:], s)
b.n += n
nn += n
s = s[n:]
b.Flush()
}
if b.err != nil { if b.err != nil {
return 0, b.err return nn, b.err
} }
// Common case, worth making fast. n := copy(b.buf[b.n:], s)
if b.Available() >= len(s) || len(b.buf) >= len(s) && b.Flush() == nil { b.n += n
for i := 0; i < len(s); i++ { // loop over bytes, not runes. nn += n
b.buf[b.n] = s[i] return nn, nil
b.n++
}
return len(s), nil
}
for i := 0; i < len(s); i++ { // loop over bytes, not runes.
b.WriteByte(s[i])
if b.err != nil {
return i, b.err
}
}
return len(s), nil
} }
// buffered input and output // buffered input and output