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 // Bytes returns a slice of the contents of the unread portion of the buffer;
37 // len(b.Bytes()) == b.Len(). If the caller changes the contents of the
38 // returned slice, the contents of the buffer will change provided there
39 // are no intervening method calls on the Buffer.
40 func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
42 // String returns the contents of the unread portion of the buffer
43 // as a string. If the Buffer is a nil pointer, it returns "<nil>".
44 func (b *Buffer) String() string {
46 // Special case, useful in debugging.
49 return string(b.buf[b.off:])
52 // Len returns the number of bytes of the unread portion of the buffer;
53 // b.Len() == len(b.Bytes()).
54 func (b *Buffer) Len() int { return len(b.buf) - b.off }
56 // Truncate discards all but the first n unread bytes from the buffer.
57 // It is an error to call b.Truncate(n) with n > b.Len().
58 func (b *Buffer) Truncate(n int) {
59 b.lastRead = opInvalid
61 // Reuse buffer space.
64 b.buf = b.buf[0 : b.off+n]
67 // Reset resets the buffer so it has no content.
68 // b.Reset() is the same as b.Truncate(0).
69 func (b *Buffer) Reset() { b.Truncate(0) }
71 // Grow buffer to guarantee space for n more bytes.
72 // Return index where bytes should be written.
73 func (b *Buffer) grow(n int) int {
75 // If buffer is empty, reset to recover space.
76 if m == 0 && b.off != 0 {
79 if len(b.buf)+n > cap(b.buf) {
81 if b.buf == nil && n <= len(b.bootstrap) {
84 // not enough space anywhere
85 buf = make([]byte, 2*cap(b.buf)+n)
86 copy(buf, b.buf[b.off:])
91 b.buf = b.buf[0 : b.off+m+n]
95 // Write appends the contents of p to the buffer. The return
96 // value n is the length of p; err is always nil.
97 func (b *Buffer) Write(p []byte) (n int, err os.Error) {
98 b.lastRead = opInvalid
104 // WriteString appends the contents of s to the buffer. The return
105 // value n is the length of s; err is always nil.
106 func (b *Buffer) WriteString(s string) (n int, err os.Error) {
107 b.lastRead = opInvalid
109 return copy(b.buf[m:], s), nil
112 // MinRead is the minimum slice size passed to a Read call by
113 // Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond
114 // what is required to hold the contents of r, ReadFrom will not grow the
115 // underlying buffer.
118 // ReadFrom reads data from r until EOF and appends it to the buffer.
119 // The return value n is the number of bytes read.
120 // Any error except os.EOF encountered during the read
122 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
123 b.lastRead = opInvalid
124 // If buffer is empty, reset to recover space.
125 if b.off >= len(b.buf) {
129 if cap(b.buf)-len(b.buf) < MinRead {
131 // can we get space without allocation?
132 if b.off+cap(b.buf)-len(b.buf) >= MinRead {
133 // reuse beginning of buffer
134 newBuf = b.buf[0 : len(b.buf)-b.off]
136 // not enough space at end; put space on end
137 newBuf = make([]byte, len(b.buf)-b.off, 2*(cap(b.buf)-b.off)+MinRead)
139 copy(newBuf, b.buf[b.off:])
143 m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
144 b.buf = b.buf[0 : len(b.buf)+m]
153 return n, nil // err is EOF, so return nil explicitly
156 // WriteTo writes data to w until the buffer is drained or an error
157 // occurs. The return value n is the number of bytes written; it always
158 // fits into an int, but it is int64 to match the io.WriterTo interface.
159 // Any error encountered during the write is also returned.
160 func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) {
161 b.lastRead = opInvalid
162 if b.off < len(b.buf) {
163 m, e := w.Write(b.buf[b.off:])
169 // otherwise all bytes were written, by definition of
170 // Write method in io.Writer
172 // Buffer is now empty; reset.
177 // WriteByte appends the byte c to the buffer.
178 // The returned error is always nil, but is included
179 // to match bufio.Writer's WriteByte.
180 func (b *Buffer) WriteByte(c byte) os.Error {
181 b.lastRead = opInvalid
187 // WriteRune appends the UTF-8 encoding of Unicode
188 // code point r to the buffer, returning its length and
189 // an error, which is always nil but is included
190 // to match bufio.Writer's WriteRune.
191 func (b *Buffer) WriteRune(r int) (n int, err os.Error) {
192 if r < utf8.RuneSelf {
196 n = utf8.EncodeRune(b.runeBytes[0:], r)
197 b.Write(b.runeBytes[0:n])
201 // Read reads the next len(p) bytes from the buffer or until the buffer
202 // is drained. The return value n is the number of bytes read. If the
203 // buffer has no data to return, err is os.EOF even if len(p) is zero;
204 // otherwise it is nil.
205 func (b *Buffer) Read(p []byte) (n int, err os.Error) {
206 b.lastRead = opInvalid
207 if b.off >= len(b.buf) {
208 // Buffer is empty, reset to recover space.
212 n = copy(p, b.buf[b.off:])
220 // Next returns a slice containing the next n bytes from the buffer,
221 // advancing the buffer as if the bytes had been returned by Read.
222 // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
223 // The slice is only valid until the next call to a read or write method.
224 func (b *Buffer) Next(n int) []byte {
225 b.lastRead = opInvalid
230 data := b.buf[b.off : b.off+n]
238 // ReadByte reads and returns the next byte from the buffer.
239 // If no byte is available, it returns error os.EOF.
240 func (b *Buffer) ReadByte() (c byte, err os.Error) {
241 b.lastRead = opInvalid
242 if b.off >= len(b.buf) {
243 // Buffer is empty, reset to recover space.
253 // ReadRune reads and returns the next UTF-8-encoded
254 // Unicode code point from the buffer.
255 // If no bytes are available, the error returned is os.EOF.
256 // If the bytes are an erroneous UTF-8 encoding, it
257 // consumes one byte and returns U+FFFD, 1.
258 func (b *Buffer) ReadRune() (r int, size int, err os.Error) {
259 b.lastRead = opInvalid
260 if b.off >= len(b.buf) {
261 // Buffer is empty, reset to recover space.
265 b.lastRead = opReadRune
267 if c < utf8.RuneSelf {
269 return int(c), 1, nil
271 r, n := utf8.DecodeRune(b.buf[b.off:])
276 // UnreadRune unreads the last rune returned by ReadRune.
277 // If the most recent read or write operation on the buffer was
278 // not a ReadRune, UnreadRune returns an error. (In this regard
279 // it is stricter than UnreadByte, which will unread the last byte
280 // from any read operation.)
281 func (b *Buffer) UnreadRune() os.Error {
282 if b.lastRead != opReadRune {
283 return os.NewError("bytes.Buffer: UnreadRune: previous operation was not ReadRune")
285 b.lastRead = opInvalid
287 _, n := utf8.DecodeLastRune(b.buf[0:b.off])
293 // UnreadByte unreads the last byte returned by the most recent
294 // read operation. If write has happened since the last read, UnreadByte
296 func (b *Buffer) UnreadByte() os.Error {
297 if b.lastRead != opReadRune && b.lastRead != opRead {
298 return os.NewError("bytes.Buffer: UnreadByte: previous operation was not a read")
300 b.lastRead = opInvalid
307 // ReadBytes reads until the first occurrence of delim in the input,
308 // returning a slice containing the data up to and including the delimiter.
309 // If ReadBytes encounters an error before finding a delimiter,
310 // it returns the data read before the error and the error itself (often os.EOF).
311 // ReadBytes returns err != nil if and only if the returned data does not end in
313 func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) {
314 i := IndexByte(b.buf[b.off:], delim)
317 size = len(b.buf) - b.off
320 line = make([]byte, size)
321 copy(line, b.buf[b.off:])
326 // ReadString reads until the first occurrence of delim in the input,
327 // returning a string containing the data up to and including the delimiter.
328 // If ReadString encounters an error before finding a delimiter,
329 // it returns the data read before the error and the error itself (often os.EOF).
330 // ReadString returns err != nil if and only if the returned data does not end
332 func (b *Buffer) ReadString(delim byte) (line string, err os.Error) {
333 bytes, err := b.ReadBytes(delim)
334 return string(bytes), err
337 // NewBuffer creates and initializes a new Buffer using buf as its initial
338 // contents. It is intended to prepare a Buffer to read existing data. It
339 // can also be used to size the internal buffer for writing. To do that,
340 // buf should have the desired capacity but a length of zero.
341 func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
343 // NewBufferString creates and initializes a new Buffer using string s as its
344 // initial contents. It is intended to prepare a buffer to read an existing
346 func NewBufferString(s string) *Buffer {
347 return &Buffer{buf: []byte(s)}