1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Simple byte buffer for marshaling data.
15 // A Buffer is a variable-sized buffer of bytes with Read and Write methods.
16 // The zero value for Buffer is an empty buffer ready to use.
18 buf []byte // contents are the bytes buf[off : len(buf)]
19 off int // read at &buf[off], write at &buf[len(buf)]
20 runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune
21 bootstrap [64]byte // memory to hold first slice; helps small buffers (Printf) avoid allocation.
22 lastRead readOp // last read operation, so that Unread* can work correctly.
25 // The readOp constants describe the last action performed on
26 // the buffer, so that UnreadRune and UnreadByte can
27 // check for invalid usage.
31 opInvalid readOp = iota // Non-read operation.
32 opReadRune // Read rune.
33 opRead // Any other read operation.
36 // ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
37 var ErrTooLarge = errors.New("bytes.Buffer: too large")
39 // Bytes returns a slice of the contents of the unread portion of the buffer;
40 // len(b.Bytes()) == b.Len(). If the caller changes the contents of the
41 // returned slice, the contents of the buffer will change provided there
42 // are no intervening method calls on the Buffer.
43 func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
45 // String returns the contents of the unread portion of the buffer
46 // as a string. If the Buffer is a nil pointer, it returns "<nil>".
47 func (b *Buffer) String() string {
49 // Special case, useful in debugging.
52 return string(b.buf[b.off:])
55 // Len returns the number of bytes of the unread portion of the buffer;
56 // b.Len() == len(b.Bytes()).
57 func (b *Buffer) Len() int { return len(b.buf) - b.off }
59 // Truncate discards all but the first n unread bytes from the buffer.
60 // It panics if n is negative or greater than the length of the buffer.
61 func (b *Buffer) Truncate(n int) {
62 b.lastRead = opInvalid
64 case n < 0 || n > b.Len():
65 panic("bytes.Buffer: truncation out of range")
67 // Reuse buffer space.
70 b.buf = b.buf[0 : b.off+n]
73 // Reset resets the buffer so it has no content.
74 // b.Reset() is the same as b.Truncate(0).
75 func (b *Buffer) Reset() { b.Truncate(0) }
77 // grow grows the buffer to guarantee space for n more bytes.
78 // It returns the index where bytes should be written.
79 // If the buffer can't grow it will panic with ErrTooLarge.
80 func (b *Buffer) grow(n int) int {
82 // If buffer is empty, reset to recover space.
83 if m == 0 && b.off != 0 {
86 if len(b.buf)+n > cap(b.buf) {
88 if b.buf == nil && n <= len(b.bootstrap) {
91 // not enough space anywhere
92 buf = makeSlice(2*cap(b.buf) + n)
93 copy(buf, b.buf[b.off:])
98 b.buf = b.buf[0 : b.off+m+n]
102 // Write appends the contents of p to the buffer. The return
103 // value n is the length of p; err is always nil.
104 // If the buffer becomes too large, Write will panic with
106 func (b *Buffer) Write(p []byte) (n int, err error) {
107 b.lastRead = opInvalid
109 return copy(b.buf[m:], p), nil
112 // WriteString appends the contents of s to the buffer. The return
113 // value n is the length of s; err is always nil.
114 // If the buffer becomes too large, WriteString will panic with
116 func (b *Buffer) WriteString(s string) (n int, err error) {
117 b.lastRead = opInvalid
119 return copy(b.buf[m:], s), nil
122 // MinRead is the minimum slice size passed to a Read call by
123 // Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond
124 // what is required to hold the contents of r, ReadFrom will not grow the
125 // underlying buffer.
128 // ReadFrom reads data from r until EOF and appends it to the buffer.
129 // The return value n is the number of bytes read.
130 // Any error except io.EOF encountered during the read
132 // If the buffer becomes too large, ReadFrom will panic with
134 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
135 b.lastRead = opInvalid
136 // If buffer is empty, reset to recover space.
137 if b.off >= len(b.buf) {
141 if free := cap(b.buf) - len(b.buf); free < MinRead {
142 // not enough space at end
144 if b.off+free < MinRead {
145 // not enough space using beginning of buffer;
146 // double buffer capacity
147 newBuf = makeSlice(2*cap(b.buf) + MinRead)
149 copy(newBuf, b.buf[b.off:])
150 b.buf = newBuf[:len(b.buf)-b.off]
153 m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
154 b.buf = b.buf[0 : len(b.buf)+m]
163 return n, nil // err is EOF, so return nil explicitly
166 // makeSlice allocates a slice of size n. If the allocation fails, it panics
168 func makeSlice(n int) []byte {
169 // If the make fails, give a known error.
171 if recover() != nil {
175 return make([]byte, n)
178 // WriteTo writes data to w until the buffer is drained or an error
179 // occurs. The return value n is the number of bytes written; it always
180 // fits into an int, but it is int64 to match the io.WriterTo interface.
181 // Any error encountered during the write is also returned.
182 func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
183 b.lastRead = opInvalid
184 if b.off < len(b.buf) {
186 m, e := w.Write(b.buf[b.off:])
188 panic("bytes.Buffer.WriteTo: invalid Write count")
195 // all bytes should have been written, by definition of
196 // Write method in io.Writer
198 return n, io.ErrShortWrite
201 // Buffer is now empty; reset.
206 // WriteByte appends the byte c to the buffer.
207 // The returned error is always nil, but is included
208 // to match bufio.Writer's WriteByte.
209 // If the buffer becomes too large, WriteByte will panic with
211 func (b *Buffer) WriteByte(c byte) error {
212 b.lastRead = opInvalid
218 // WriteRune appends the UTF-8 encoding of Unicode
219 // code point r to the buffer, returning its length and
220 // an error, which is always nil but is included
221 // to match bufio.Writer's WriteRune.
222 // If the buffer becomes too large, WriteRune will panic with
224 func (b *Buffer) WriteRune(r rune) (n int, err error) {
225 if r < utf8.RuneSelf {
229 n = utf8.EncodeRune(b.runeBytes[0:], r)
230 b.Write(b.runeBytes[0:n])
234 // Read reads the next len(p) bytes from the buffer or until the buffer
235 // is drained. The return value n is the number of bytes read. If the
236 // buffer has no data to return, err is io.EOF (unless len(p) is zero);
237 // otherwise it is nil.
238 func (b *Buffer) Read(p []byte) (n int, err error) {
239 b.lastRead = opInvalid
240 if b.off >= len(b.buf) {
241 // Buffer is empty, reset to recover space.
248 n = copy(p, b.buf[b.off:])
256 // Next returns a slice containing the next n bytes from the buffer,
257 // advancing the buffer as if the bytes had been returned by Read.
258 // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
259 // The slice is only valid until the next call to a read or write method.
260 func (b *Buffer) Next(n int) []byte {
261 b.lastRead = opInvalid
266 data := b.buf[b.off : b.off+n]
274 // ReadByte reads and returns the next byte from the buffer.
275 // If no byte is available, it returns error io.EOF.
276 func (b *Buffer) ReadByte() (c byte, err error) {
277 b.lastRead = opInvalid
278 if b.off >= len(b.buf) {
279 // Buffer is empty, reset to recover space.
289 // ReadRune reads and returns the next UTF-8-encoded
290 // Unicode code point from the buffer.
291 // If no bytes are available, the error returned is io.EOF.
292 // If the bytes are an erroneous UTF-8 encoding, it
293 // consumes one byte and returns U+FFFD, 1.
294 func (b *Buffer) ReadRune() (r rune, size int, err error) {
295 b.lastRead = opInvalid
296 if b.off >= len(b.buf) {
297 // Buffer is empty, reset to recover space.
301 b.lastRead = opReadRune
303 if c < utf8.RuneSelf {
305 return rune(c), 1, nil
307 r, n := utf8.DecodeRune(b.buf[b.off:])
312 // UnreadRune unreads the last rune returned by ReadRune.
313 // If the most recent read or write operation on the buffer was
314 // not a ReadRune, UnreadRune returns an error. (In this regard
315 // it is stricter than UnreadByte, which will unread the last byte
316 // from any read operation.)
317 func (b *Buffer) UnreadRune() error {
318 if b.lastRead != opReadRune {
319 return errors.New("bytes.Buffer: UnreadRune: previous operation was not ReadRune")
321 b.lastRead = opInvalid
323 _, n := utf8.DecodeLastRune(b.buf[0:b.off])
329 // UnreadByte unreads the last byte returned by the most recent
330 // read operation. If write has happened since the last read, UnreadByte
332 func (b *Buffer) UnreadByte() error {
333 if b.lastRead != opReadRune && b.lastRead != opRead {
334 return errors.New("bytes.Buffer: UnreadByte: previous operation was not a read")
336 b.lastRead = opInvalid
343 // ReadBytes reads until the first occurrence of delim in the input,
344 // returning a slice containing the data up to and including the delimiter.
345 // If ReadBytes encounters an error before finding a delimiter,
346 // it returns the data read before the error and the error itself (often io.EOF).
347 // ReadBytes returns err != nil if and only if the returned data does not end in
349 func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
350 i := IndexByte(b.buf[b.off:], delim)
353 size = len(b.buf) - b.off
356 line = make([]byte, size)
357 copy(line, b.buf[b.off:])
362 // ReadString reads until the first occurrence of delim in the input,
363 // returning a string containing the data up to and including the delimiter.
364 // If ReadString encounters an error before finding a delimiter,
365 // it returns the data read before the error and the error itself (often io.EOF).
366 // ReadString returns err != nil if and only if the returned data does not end
368 func (b *Buffer) ReadString(delim byte) (line string, err error) {
369 bytes, err := b.ReadBytes(delim)
370 return string(bytes), err
373 // NewBuffer creates and initializes a new Buffer using buf as its initial
374 // contents. It is intended to prepare a Buffer to read existing data. It
375 // can also be used to size the internal buffer for writing. To do that,
376 // buf should have the desired capacity but a length of zero.
378 // In most cases, new(Buffer) (or just declaring a Buffer variable) is
379 // sufficient to initialize a Buffer.
380 func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
382 // NewBufferString creates and initializes a new Buffer using string s as its
383 // initial contents. It is intended to prepare a buffer to read an existing
386 // In most cases, new(Buffer) (or just declaring a Buffer variable) is
387 // sufficient to initialize a Buffer.
388 func NewBufferString(s string) *Buffer {
389 return &Buffer{buf: []byte(s)}