1// Copyright 2009 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.45package bytes67// Simple byte buffer for marshaling data.89import (10 "errors"11 "io"12 "unicode/utf8"13)1415// smallBufferSize is an initial allocation minimal capacity.16const smallBufferSize = 641718// A Buffer is a variable-sized buffer of bytes with [Buffer.Read] and [Buffer.Write] methods.19// The zero value for Buffer is an empty buffer ready to use.20type Buffer struct {21 buf []byte // contents are the bytes buf[off : len(buf)]22 off int // read at &buf[off], write at &buf[len(buf)]23 lastRead readOp // last read operation, so that Unread* can work correctly.2425 // Copying and modifying a non-zero Buffer is prone to error,26 // but we cannot employ the noCopy trick used by WaitGroup and Mutex,27 // which causes vet's copylocks checker to report misuse, as vet28 // cannot reliably distinguish the zero and non-zero cases.29 // See #26462, #25907, #47276, #48398 for history.30}3132// The readOp constants describe the last action performed on33// the buffer, so that UnreadRune and UnreadByte can check for34// invalid usage. opReadRuneX constants are chosen such that35// converted to int they correspond to the rune size that was read.36type readOp int83738// Don't use iota for these, as the values need to correspond with the39// names and comments, which is easier to see when being explicit.40const (41 opRead readOp = -1 // Any other read operation.42 opInvalid readOp = 0 // Non-read operation.43 opReadRune1 readOp = 1 // Read rune of size 1.44 opReadRune2 readOp = 2 // Read rune of size 2.45 opReadRune3 readOp = 3 // Read rune of size 3.46 opReadRune4 readOp = 4 // Read rune of size 4.47)4849// ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.50var ErrTooLarge = errors.New("bytes.Buffer: too large")51var errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read")5253const maxInt = int(^uint(0) >> 1)5455// Bytes returns a slice of length b.Len() holding the unread portion of the buffer.56// The slice is valid for use only until the next buffer modification (that is,57// only until the next call to a method like [Buffer.Read], [Buffer.Write], [Buffer.Reset], or [Buffer.Truncate]).58// The slice aliases the buffer content at least until the next buffer modification,59// so immediate changes to the slice will affect the result of future reads.60func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }6162// AvailableBuffer returns an empty buffer with b.Available() capacity.63// This buffer is intended to be appended to and64// passed to an immediately succeeding [Buffer.Write] call.65// The buffer is only valid until the next write operation on b.66func (b *Buffer) AvailableBuffer() []byte { return b.buf[len(b.buf):] }6768// String returns the contents of the unread portion of the buffer69// as a string. If the [Buffer] is a nil pointer, it returns "<nil>".70//71// To build strings more efficiently, see the [strings.Builder] type.72func (b *Buffer) String() string {73 if b == nil {74 // Special case, useful in debugging.75 return "<nil>"76 }77 return string(b.buf[b.off:])78}7980// Peek returns the next n bytes without advancing the buffer.81// If Peek returns fewer than n bytes, it also returns [io.EOF].82// The slice is only valid until the next call to a read or write method.83// The slice aliases the buffer content at least until the next buffer modification,84// so immediate changes to the slice will affect the result of future reads.85func (b *Buffer) Peek(n int) ([]byte, error) {86 if b.Len() < n {87 return b.buf[b.off:], io.EOF88 }89 return b.buf[b.off : b.off+n], nil90}9192// empty reports whether the unread portion of the buffer is empty.93func (b *Buffer) empty() bool { return len(b.buf) <= b.off }9495// Len returns the number of bytes of the unread portion of the buffer;96// b.Len() == len(b.Bytes()).97func (b *Buffer) Len() int { return len(b.buf) - b.off }9899// Cap returns the capacity of the buffer's underlying byte slice, that is, the100// total space allocated for the buffer's data.101func (b *Buffer) Cap() int { return cap(b.buf) }102103// Available returns how many bytes are unused in the buffer.104func (b *Buffer) Available() int { return cap(b.buf) - len(b.buf) }105106// Truncate discards all but the first n unread bytes from the buffer107// but continues to use the same allocated storage.108// It panics if n is negative or greater than the length of the buffer.109func (b *Buffer) Truncate(n int) {110 if n == 0 {111 b.Reset()112 return113 }114 b.lastRead = opInvalid115 if n < 0 || n > b.Len() {116 panic("bytes.Buffer: truncation out of range")117 }118 b.buf = b.buf[:b.off+n]119}120121// Reset resets the buffer to be empty,122// but it retains the underlying storage for use by future writes.123// Reset is the same as [Buffer.Truncate](0).124func (b *Buffer) Reset() {125 b.buf = b.buf[:0]126 b.off = 0127 b.lastRead = opInvalid128}129130// tryGrowByReslice is an inlineable version of grow for the fast-case where the131// internal buffer only needs to be resliced.132// It returns the index where bytes should be written and whether it succeeded.133func (b *Buffer) tryGrowByReslice(n int) (int, bool) {134 if l := len(b.buf); n <= cap(b.buf)-l {135 b.buf = b.buf[:l+n]136 return l, true137 }138 return 0, false139}140141// grow grows the buffer to guarantee space for n more bytes.142// It returns the index where bytes should be written.143// If the buffer can't grow it will panic with ErrTooLarge.144func (b *Buffer) grow(n int) int {145 m := b.Len()146 // If buffer is empty, reset to recover space.147 if m == 0 && b.off != 0 {148 b.Reset()149 }150 // Try to grow by means of a reslice.151 if i, ok := b.tryGrowByReslice(n); ok {152 return i153 }154 if b.buf == nil && n <= smallBufferSize {155 b.buf = make([]byte, n, smallBufferSize)156 return 0157 }158 c := cap(b.buf)159 if n <= c/2-m {160 // We can slide things down instead of allocating a new161 // slice. We only need m+n <= c to slide, but162 // we instead let capacity get twice as large so we163 // don't spend all our time copying.164 copy(b.buf, b.buf[b.off:])165 } else if c > maxInt-c-n {166 panic(ErrTooLarge)167 } else {168 // Add b.off to account for b.buf[:b.off] being sliced off the front.169 b.buf = growSlice(b.buf[b.off:], b.off+n)170 }171 // Restore b.off and len(b.buf).172 b.off = 0173 b.buf = b.buf[:m+n]174 return m175}176177// Grow grows the buffer's capacity, if necessary, to guarantee space for178// another n bytes. After Grow(n), at least n bytes can be written to the179// buffer without another allocation.180// If n is negative, Grow will panic.181// If the buffer can't grow it will panic with [ErrTooLarge].182func (b *Buffer) Grow(n int) {183 if n < 0 {184 panic("bytes.Buffer.Grow: negative count")185 }186 m := b.grow(n)187 b.buf = b.buf[:m]188}189190// Write appends the contents of p to the buffer, growing the buffer as191// needed. The return value n is the length of p; err is always nil. If the192// buffer becomes too large, Write will panic with [ErrTooLarge].193func (b *Buffer) Write(p []byte) (n int, err error) {194 b.lastRead = opInvalid195 m, ok := b.tryGrowByReslice(len(p))196 if !ok {197 m = b.grow(len(p))198 }199 return copy(b.buf[m:], p), nil200}201202// WriteString appends the contents of s to the buffer, growing the buffer as203// needed. The return value n is the length of s; err is always nil. If the204// buffer becomes too large, WriteString will panic with [ErrTooLarge].205func (b *Buffer) WriteString(s string) (n int, err error) {206 b.lastRead = opInvalid207 m, ok := b.tryGrowByReslice(len(s))208 if !ok {209 m = b.grow(len(s))210 }211 return copy(b.buf[m:], s), nil212}213214// MinRead is the minimum slice size passed to a [Buffer.Read] call by215// [Buffer.ReadFrom]. As long as the [Buffer] has at least MinRead bytes beyond216// what is required to hold the contents of r, [Buffer.ReadFrom] will not grow the217// underlying buffer.218const MinRead = 512219220// ReadFrom reads data from r until EOF and appends it to the buffer, growing221// the buffer as needed. The return value n is the number of bytes read. Any222// error except io.EOF encountered during the read is also returned. If the223// buffer becomes too large, ReadFrom will panic with [ErrTooLarge].224func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {225 b.lastRead = opInvalid226 for {227 i := b.grow(MinRead)228 b.buf = b.buf[:i]229 m, e := r.Read(b.buf[i:cap(b.buf)])230 if m < 0 {231 panic(errNegativeRead)232 }233234 b.buf = b.buf[:i+m]235 n += int64(m)236 if e == io.EOF {237 return n, nil // e is EOF, so return nil explicitly238 }239 if e != nil {240 return n, e241 }242 }243}244245// growSlice grows b by n, preserving the original content of b.246// If the allocation fails, it panics with ErrTooLarge.247func growSlice(b []byte, n int) []byte {248 defer func() {249 if recover() != nil {250 panic(ErrTooLarge)251 }252 }()253 // TODO(http://golang.org/issue/51462): We should rely on the append-make254 // pattern so that the compiler can call runtime.growslice. For example:255 // return append(b, make([]byte, n)...)256 // This avoids unnecessary zero-ing of the first len(b) bytes of the257 // allocated slice, but this pattern causes b to escape onto the heap.258 //259 // Instead use the append-make pattern with a nil slice to ensure that260 // we allocate buffers rounded up to the closest size class.261 c := len(b) + n // ensure enough space for n elements262 if c < 2*cap(b) {263 // The growth rate has historically always been 2x. In the future,264 // we could rely purely on append to determine the growth rate.265 c = 2 * cap(b)266 }267 b2 := append([]byte(nil), make([]byte, c)...)268 i := copy(b2, b)269 return b2[:i]270}271272// WriteTo writes data to w until the buffer is drained or an error occurs.273// The return value n is the number of bytes written; it always fits into an274// int, but it is int64 to match the [io.WriterTo] interface. Any error275// encountered during the write is also returned.276func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {277 b.lastRead = opInvalid278 if nBytes := b.Len(); nBytes > 0 {279 m, e := w.Write(b.buf[b.off:])280 if m > nBytes {281 panic("bytes.Buffer.WriteTo: invalid Write count")282 }283 b.off += m284 n = int64(m)285 if e != nil {286 return n, e287 }288 // all bytes should have been written, by definition of289 // Write method in io.Writer290 if m != nBytes {291 return n, io.ErrShortWrite292 }293 }294 // Buffer is now empty; reset.295 b.Reset()296 return n, nil297}298299// WriteByte appends the byte c to the buffer, growing the buffer as needed.300// The returned error is always nil, but is included to match [bufio.Writer]'s301// WriteByte. If the buffer becomes too large, WriteByte will panic with302// [ErrTooLarge].303func (b *Buffer) WriteByte(c byte) error {304 b.lastRead = opInvalid305 m, ok := b.tryGrowByReslice(1)306 if !ok {307 m = b.grow(1)308 }309 b.buf[m] = c310 return nil311}312313// WriteRune appends the UTF-8 encoding of Unicode code point r to the314// buffer, returning the number of bytes written and a nil error. The nil315// error is included to match [bufio.Writer]'s WriteRune. The buffer is grown316// as needed; if it becomes too large, WriteRune will panic with [ErrTooLarge].317func (b *Buffer) WriteRune(r rune) (n int, err error) {318 // Compare as uint32 to correctly handle negative runes.319 if uint32(r) < utf8.RuneSelf {320 b.WriteByte(byte(r))321 return 1, nil322 }323 b.lastRead = opInvalid324 m, ok := b.tryGrowByReslice(utf8.UTFMax)325 if !ok {326 m = b.grow(utf8.UTFMax)327 }328 b.buf = utf8.AppendRune(b.buf[:m], r)329 return len(b.buf) - m, nil330}331332// Read reads the next len(p) bytes from the buffer or until the buffer333// is drained. The return value n is the number of bytes read. If the334// buffer has no data to return, err is [io.EOF] (unless len(p) is zero);335// otherwise it is nil.336func (b *Buffer) Read(p []byte) (n int, err error) {337 b.lastRead = opInvalid338 if b.empty() {339 // Buffer is empty, reset to recover space.340 b.Reset()341 if len(p) == 0 {342 return 0, nil343 }344 return 0, io.EOF345 }346 n = copy(p, b.buf[b.off:])347 b.off += n348 if n > 0 {349 b.lastRead = opRead350 }351 return n, nil352}353354// Next returns a slice containing the next n bytes from the buffer,355// advancing the buffer as if the bytes had been returned by [Buffer.Read].356// If there are fewer than n bytes in the buffer, Next returns the entire buffer.357// The slice is only valid until the next call to a read or write method.358func (b *Buffer) Next(n int) []byte {359 b.lastRead = opInvalid360 m := b.Len()361 if n > m {362 n = m363 }364 data := b.buf[b.off : b.off+n]365 b.off += n366 if n > 0 {367 b.lastRead = opRead368 }369 return data370}371372// ReadByte reads and returns the next byte from the buffer.373// If no byte is available, it returns error [io.EOF].374func (b *Buffer) ReadByte() (byte, error) {375 if b.empty() {376 // Buffer is empty, reset to recover space.377 b.Reset()378 return 0, io.EOF379 }380 c := b.buf[b.off]381 b.off++382 b.lastRead = opRead383 return c, nil384}385386// ReadRune reads and returns the next UTF-8-encoded387// Unicode code point from the buffer.388// If no bytes are available, the error returned is io.EOF.389// If the bytes are an erroneous UTF-8 encoding, it390// consumes one byte and returns U+FFFD, 1.391func (b *Buffer) ReadRune() (r rune, size int, err error) {392 if b.empty() {393 // Buffer is empty, reset to recover space.394 b.Reset()395 return 0, 0, io.EOF396 }397 c := b.buf[b.off]398 if c < utf8.RuneSelf {399 b.off++400 b.lastRead = opReadRune1401 return rune(c), 1, nil402 }403 r, n := utf8.DecodeRune(b.buf[b.off:])404 b.off += n405 b.lastRead = readOp(n)406 return r, n, nil407}408409// UnreadRune unreads the last rune returned by [Buffer.ReadRune].410// If the most recent read or write operation on the buffer was411// not a successful [Buffer.ReadRune], UnreadRune returns an error. (In this regard412// it is stricter than [Buffer.UnreadByte], which will unread the last byte413// from any read operation.)414func (b *Buffer) UnreadRune() error {415 if b.lastRead <= opInvalid {416 return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune")417 }418 if b.off >= int(b.lastRead) {419 b.off -= int(b.lastRead)420 }421 b.lastRead = opInvalid422 return nil423}424425var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read")426427// UnreadByte unreads the last byte returned by the most recent successful428// read operation that read at least one byte. If a write has happened since429// the last read, if the last read returned an error, or if the read read zero430// bytes, UnreadByte returns an error.431func (b *Buffer) UnreadByte() error {432 if b.lastRead == opInvalid {433 return errUnreadByte434 }435 b.lastRead = opInvalid436 if b.off > 0 {437 b.off--438 }439 return nil440}441442// ReadBytes reads until the first occurrence of delim in the input,443// returning a slice containing the data up to and including the delimiter.444// If ReadBytes encounters an error before finding a delimiter,445// it returns the data read before the error and the error itself (often [io.EOF]).446// ReadBytes returns err != nil if and only if the returned data does not end in447// delim.448func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {449 slice, err := b.readSlice(delim)450 // return a copy of slice. The buffer's backing array may451 // be overwritten by later calls.452 line = append(line, slice...)453 return line, err454}455456// readSlice is like ReadBytes but returns a reference to internal buffer data.457func (b *Buffer) readSlice(delim byte) (line []byte, err error) {458 i := IndexByte(b.buf[b.off:], delim)459 end := b.off + i + 1460 if i < 0 {461 end = len(b.buf)462 err = io.EOF463 }464 line = b.buf[b.off:end]465 b.off = end466 b.lastRead = opRead467 return line, err468}469470// ReadString reads until the first occurrence of delim in the input,471// returning a string containing the data up to and including the delimiter.472// If ReadString encounters an error before finding a delimiter,473// it returns the data read before the error and the error itself (often [io.EOF]).474// ReadString returns err != nil if and only if the returned data does not end475// in delim.476func (b *Buffer) ReadString(delim byte) (line string, err error) {477 slice, err := b.readSlice(delim)478 return string(slice), err479}480481// NewBuffer creates and initializes a new [Buffer] using buf as its482// initial contents. The new [Buffer] takes ownership of buf, and the483// caller should not use buf after this call. NewBuffer is intended to484// prepare a [Buffer] to read existing data. It can also be used to set485// the initial size of the internal buffer for writing. To do that,486// buf should have the desired capacity but a length of zero.487//488// In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is489// sufficient to initialize a [Buffer].490func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }491492// NewBufferString creates and initializes a new [Buffer] using string s as its493// initial contents. It is intended to prepare a buffer to read an existing494// string.495//496// In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is497// sufficient to initialize a [Buffer].498func NewBufferString(s string) *Buffer {499 return &Buffer{buf: []byte(s)}500}
Findings
✓ No findings reported for this file.