Commit 0a75a79c authored by Rob Pike's avatar Rob Pike

bytes: API tweaks

- fix documentation for NewBuffer and NewBufferString
- document and implement behavior of Truncate on invalid lengths

Fixes #2837.

R=rsc, adg
CC=golang-dev
https://golang.org/cl/5637044
parent 929203ac
...@@ -57,10 +57,13 @@ func (b *Buffer) String() string { ...@@ -57,10 +57,13 @@ func (b *Buffer) String() string {
func (b *Buffer) Len() int { return len(b.buf) - b.off } func (b *Buffer) Len() int { return len(b.buf) - b.off }
// Truncate discards all but the first n unread bytes from the buffer. // Truncate discards all but the first n unread bytes from the buffer.
// It is an error to call b.Truncate(n) with n > b.Len(). // It panics if n is negative or greater than the length of the buffer.
func (b *Buffer) Truncate(n int) { func (b *Buffer) Truncate(n int) {
b.lastRead = opInvalid b.lastRead = opInvalid
if n == 0 { switch {
case n < 0 || n > b.Len():
panic("bytes.Buffer: truncation out of range")
case n == 0:
// Reuse buffer space. // Reuse buffer space.
b.off = 0 b.off = 0
} }
...@@ -366,14 +369,15 @@ func (b *Buffer) ReadString(delim byte) (line string, err error) { ...@@ -366,14 +369,15 @@ func (b *Buffer) ReadString(delim byte) (line string, err error) {
// buf should have the desired capacity but a length of zero. // buf should have the desired capacity but a length of zero.
// //
// In most cases, new(Buffer) (or just declaring a Buffer variable) is // In most cases, new(Buffer) (or just declaring a Buffer variable) is
// preferable to NewBuffer. In particular, passing a non-empty buf to // sufficient to initialize a Buffer.
// NewBuffer and then writing to the Buffer will overwrite buf, not append to
// it.
func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} } func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
// NewBufferString creates and initializes a new Buffer using string s as its // NewBufferString creates and initializes a new Buffer using string s as its
// initial contents. It is intended to prepare a buffer to read an existing // initial contents. It is intended to prepare a buffer to read an existing
// string. See the warnings about NewBuffer; similar issues apply here. // string.
//
// In most cases, new(Buffer) (or just declaring a Buffer variable) is
// sufficient to initialize a Buffer.
func NewBufferString(s string) *Buffer { func NewBufferString(s string) *Buffer {
return &Buffer{buf: []byte(s)} return &Buffer{buf: []byte(s)}
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment