| 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. |
| 4 | |
| 5 | package bufio |
| 6 | |
| 7 | // Simple byte buffer for marshaling data. |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "errors" |
| 12 | "io" |
| 13 | "unicode/utf8" |
| 14 | ) |
| 15 | |
| 16 | // A Buffer is a variable-sized buffer of bytes with Read and Write methods. |
| 17 | // The zero value for Buffer is an empty buffer ready to use. |
| 18 | type Buffer struct { |
| 19 | buf []byte // contents are the bytes buf[off : len(buf)] |
| 20 | off int // read at &buf[off], write at &buf[len(buf)] |
| 21 | runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune |
| 22 | bootstrap [64]byte // memory to hold first slice; helps small buffers (Printf) avoid allocation. |
| 23 | lastRead readOp // last read operation, so that Unread* can work correctly. |
| 24 | } |
| 25 | |
| 26 | // The readOp constants describe the last action performed on |
| 27 | // the buffer, so that UnreadRune and UnreadByte can |
| 28 | // check for invalid usage. |
| 29 | type readOp int |
| 30 | |
| 31 | const ( |
| 32 | opInvalid readOp = iota // Non-read operation. |
| 33 | opReadRune // Read rune. |
| 34 | opRead // Any other read operation. |
| 35 | ) |
| 36 | |
| 37 | // ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer. |
| 38 | var ErrTooLarge = errors.New("bytes.Buffer: too large") |
| 39 | |
| 40 | // Bytes returns a slice of the contents of the unread portion of the buffer; |
| 41 | // len(b.Bytes()) == b.Len(). If the caller changes the contents of the |
| 42 | // returned slice, the contents of the buffer will change provided there |
| 43 | // are no intervening method calls on the Buffer. |
| 44 | func (b *Buffer) Bytes() []byte { return b.buf[b.off:] } |
| 45 | |
| 46 | // String returns the contents of the unread portion of the buffer |
| 47 | // as a string. If the Buffer is a nil pointer, it returns "<nil>". |
| 48 | func (b *Buffer) String() string { |
| 49 | if b == nil { |
| 50 | // Special case, useful in debugging. |
| 51 | return "<nil>" |
| 52 | } |
| 53 | return string(b.buf[b.off:]) |
| 54 | } |
| 55 | |
| 56 | // Len returns the number of bytes of the unread portion of the buffer; |
| 57 | // b.Len() == len(b.Bytes()). |
| 58 | func (b *Buffer) Len() int { return len(b.buf) - b.off } |
| 59 | |
| 60 | // Truncate discards all but the first n unread bytes from the buffer. |
| 61 | // It panics if n is negative or greater than the length of the buffer. |
| 62 | func (b *Buffer) Truncate(n int) { |
| 63 | b.lastRead = opInvalid |
| 64 | switch { |
| 65 | case n < 0 || n > b.Len(): |
| 66 | panic("bytes.Buffer: truncation out of range") |
| 67 | case n == 0: |
| 68 | // Reuse buffer space. |
| 69 | b.off = 0 |
| 70 | } |
| 71 | b.buf = b.buf[0 : b.off+n] |
| 72 | } |
| 73 | |
| 74 | // Reset resets the buffer so it has no content. |
| 75 | // b.Reset() is the same as b.Truncate(0). |
| 76 | func (b *Buffer) Reset() { b.Truncate(0) } |
| 77 | |
| 78 | // grow grows the buffer to guarantee space for n more bytes. |
| 79 | // It returns the index where bytes should be written. |
| 80 | // If the buffer can't grow it will panic with ErrTooLarge. |
| 81 | func (b *Buffer) grow(n int) int { |
| 82 | m := b.Len() |
| 83 | // If buffer is empty, reset to recover space. |
| 84 | if m == 0 && b.off != 0 { |
| 85 | b.Truncate(0) |
| 86 | } |
| 87 | if len(b.buf)+n > cap(b.buf) { |
| 88 | var buf []byte |
| 89 | if b.buf == nil && n <= len(b.bootstrap) { |
| 90 | buf = b.bootstrap[0:] |
| 91 | } else if m+n <= cap(b.buf)/2 { |
| 92 | // We can slide things down instead of allocating a new |
| 93 | // slice. We only need m+n <= cap(b.buf) to slide, but |
| 94 | // we instead let capacity get twice as large so we |
| 95 | // don't spend all our time copying. |
| 96 | copy(b.buf[:], b.buf[b.off:]) |
| 97 | buf = b.buf[:m] |
| 98 | } else { |
| 99 | // not enough space anywhere |
| 100 | buf = makeSlice(2*cap(b.buf) + n) |
| 101 | copy(buf, b.buf[b.off:]) |
| 102 | } |
| 103 | b.buf = buf |
| 104 | b.off = 0 |
| 105 | } |
| 106 | b.buf = b.buf[0 : b.off+m+n] |
| 107 | return b.off + m |
| 108 | } |
| 109 | |
| 110 | // Grow grows the buffer's capacity, if necessary, to guarantee space for |
| 111 | // another n bytes. After Grow(n), at least n bytes can be written to the |
| 112 | // buffer without another allocation. |
| 113 | // If n is negative, Grow will panic. |
| 114 | // If the buffer can't grow it will panic with ErrTooLarge. |
| 115 | func (b *Buffer) Grow(n int) { |
| 116 | if n < 0 { |
| 117 | panic("bytes.Buffer.Grow: negative count") |
| 118 | } |
| 119 | m := b.grow(n) |
| 120 | b.buf = b.buf[0:m] |
| 121 | } |
| 122 | |
| 123 | // Write appends the contents of p to the buffer, growing the buffer as |
| 124 | // needed. The return value n is the length of p; err is always nil. If the |
| 125 | // buffer becomes too large, Write will panic with ErrTooLarge. |
| 126 | func (b *Buffer) Write(p []byte) (n int, err error) { |
| 127 | b.lastRead = opInvalid |
| 128 | m := b.grow(len(p)) |
| 129 | return copy(b.buf[m:], p), nil |
| 130 | } |
| 131 | |
| 132 | // WriteString appends the contents of s to the buffer, growing the buffer as |
| 133 | // needed. The return value n is the length of s; err is always nil. If the |
| 134 | // buffer becomes too large, WriteString will panic with ErrTooLarge. |
| 135 | func (b *Buffer) WriteString(s string) (n int, err error) { |
| 136 | b.lastRead = opInvalid |
| 137 | m := b.grow(len(s)) |
| 138 | return copy(b.buf[m:], s), nil |
| 139 | } |
| 140 | |
| 141 | // MinRead is the minimum slice size passed to a Read call by |
| 142 | // Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond |
| 143 | // what is required to hold the contents of r, ReadFrom will not grow the |
| 144 | // underlying buffer. |
| 145 | const MinRead = 512 |
| 146 | |
| 147 | // ReadFrom reads data from r until EOF and appends it to the buffer, growing |
| 148 | // the buffer as needed. The return value n is the number of bytes read. Any |
| 149 | // error except io.EOF encountered during the read is also returned. If the |
| 150 | // buffer becomes too large, ReadFrom will panic with ErrTooLarge. |
| 151 | func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) { |
| 152 | b.lastRead = opInvalid |
| 153 | // If buffer is empty, reset to recover space. |
| 154 | if b.off >= len(b.buf) { |
| 155 | b.Truncate(0) |
| 156 | } |
| 157 | for { |
| 158 | if free := cap(b.buf) - len(b.buf); free < MinRead { |
| 159 | // not enough space at end |
| 160 | newBuf := b.buf |
| 161 | if b.off+free < MinRead { |
| 162 | // not enough space using beginning of buffer; |
| 163 | // double buffer capacity |
| 164 | newBuf = makeSlice(2*cap(b.buf) + MinRead) |
| 165 | } |
| 166 | copy(newBuf, b.buf[b.off:]) |
| 167 | b.buf = newBuf[:len(b.buf)-b.off] |
| 168 | b.off = 0 |
| 169 | } |
| 170 | m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]) |
| 171 | b.buf = b.buf[0 : len(b.buf)+m] |
| 172 | n += int64(m) |
| 173 | if e == io.EOF { |
| 174 | break |
| 175 | } |
| 176 | if e != nil { |
| 177 | return n, e |
| 178 | } |
| 179 | } |
| 180 | return n, nil // err is EOF, so return nil explicitly |
| 181 | } |
| 182 | |
| 183 | // makeSlice allocates a slice of size n. If the allocation fails, it panics |
| 184 | // with ErrTooLarge. |
| 185 | func makeSlice(n int) []byte { |
| 186 | // If the make fails, give a known error. |
| 187 | defer func() { |
| 188 | if recover() != nil { |
| 189 | panic(ErrTooLarge) |
| 190 | } |
| 191 | }() |
| 192 | return make([]byte, n) |
| 193 | } |
| 194 | |
| 195 | // WriteTo writes data to w until the buffer is drained or an error occurs. |
| 196 | // The return value n is the number of bytes written; it always fits into an |
| 197 | // int, but it is int64 to match the io.WriterTo interface. Any error |
| 198 | // encountered during the write is also returned. |
| 199 | func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) { |
| 200 | b.lastRead = opInvalid |
| 201 | if b.off < len(b.buf) { |
| 202 | nBytes := b.Len() |
| 203 | m, e := w.Write(b.buf[b.off:]) |
| 204 | if m > nBytes { |
| 205 | panic("bytes.Buffer.WriteTo: invalid Write count") |
| 206 | } |
| 207 | b.off += m |
| 208 | n = int64(m) |
| 209 | if e != nil { |
| 210 | return n, e |
| 211 | } |
| 212 | // all bytes should have been written, by definition of |
| 213 | // Write method in io.Writer |
| 214 | if m != nBytes { |
| 215 | return n, io.ErrShortWrite |
| 216 | } |
| 217 | } |
| 218 | // Buffer is now empty; reset. |
| 219 | b.Truncate(0) |
| 220 | return |
| 221 | } |
| 222 | |
| 223 | // WriteByte appends the byte c to the buffer, growing the buffer as needed. |
| 224 | // The returned error is always nil, but is included to match bufio.Writer's |
| 225 | // WriteByte. If the buffer becomes too large, WriteByte will panic with |
| 226 | // ErrTooLarge. |
| 227 | func (b *Buffer) WriteByte(c byte) error { |
| 228 | b.lastRead = opInvalid |
| 229 | m := b.grow(1) |
| 230 | b.buf[m] = c |
| 231 | return nil |
| 232 | } |
| 233 | |
| 234 | // WriteRune appends the UTF-8 encoding of Unicode code point r to the |
| 235 | // buffer, returning its length and an error, which is always nil but is |
| 236 | // included to match bufio.Writer's WriteRune. The buffer is grown as needed; |
| 237 | // if it becomes too large, WriteRune will panic with ErrTooLarge. |
| 238 | func (b *Buffer) WriteRune(r rune) (n int, err error) { |
| 239 | if r < utf8.RuneSelf { |
| 240 | b.WriteByte(byte(r)) |
| 241 | return 1, nil |
| 242 | } |
| 243 | n = utf8.EncodeRune(b.runeBytes[0:], r) |
| 244 | b.Write(b.runeBytes[0:n]) |
| 245 | return n, nil |
| 246 | } |
| 247 | |
| 248 | // Read reads the next len(p) bytes from the buffer or until the buffer |
| 249 | // is drained. The return value n is the number of bytes read. If the |
| 250 | // buffer has no data to return, err is io.EOF (unless len(p) is zero); |
| 251 | // otherwise it is nil. |
| 252 | func (b *Buffer) Read(p []byte) (n int, err error) { |
| 253 | b.lastRead = opInvalid |
| 254 | if b.off >= len(b.buf) { |
| 255 | // Buffer is empty, reset to recover space. |
| 256 | b.Truncate(0) |
| 257 | if len(p) == 0 { |
| 258 | return |
| 259 | } |
| 260 | return 0, io.EOF |
| 261 | } |
| 262 | n = copy(p, b.buf[b.off:]) |
| 263 | b.off += n |
| 264 | if n > 0 { |
| 265 | b.lastRead = opRead |
| 266 | } |
| 267 | return |
| 268 | } |
| 269 | |
| 270 | // Next returns a slice containing the next n bytes from the buffer, |
| 271 | // advancing the buffer as if the bytes had been returned by Read. |
| 272 | // If there are fewer than n bytes in the buffer, Next returns the entire buffer. |
| 273 | // The slice is only valid until the next call to a read or write method. |
| 274 | func (b *Buffer) Next(n int) []byte { |
| 275 | b.lastRead = opInvalid |
| 276 | m := b.Len() |
| 277 | if n > m { |
| 278 | n = m |
| 279 | } |
| 280 | data := b.buf[b.off : b.off+n] |
| 281 | b.off += n |
| 282 | if n > 0 { |
| 283 | b.lastRead = opRead |
| 284 | } |
| 285 | return data |
| 286 | } |
| 287 | |
| 288 | // ReadByte reads and returns the next byte from the buffer. |
| 289 | // If no byte is available, it returns error io.EOF. |
| 290 | func (b *Buffer) ReadByte() (c byte, err error) { |
| 291 | b.lastRead = opInvalid |
| 292 | if b.off >= len(b.buf) { |
| 293 | // Buffer is empty, reset to recover space. |
| 294 | b.Truncate(0) |
| 295 | return 0, io.EOF |
| 296 | } |
| 297 | c = b.buf[b.off] |
| 298 | b.off++ |
| 299 | b.lastRead = opRead |
| 300 | return c, nil |
| 301 | } |
| 302 | |
| 303 | // ReadRune reads and returns the next UTF-8-encoded |
| 304 | // Unicode code point from the buffer. |
| 305 | // If no bytes are available, the error returned is io.EOF. |
| 306 | // If the bytes are an erroneous UTF-8 encoding, it |
| 307 | // consumes one byte and returns U+FFFD, 1. |
| 308 | func (b *Buffer) ReadRune() (r rune, size int, err error) { |
| 309 | b.lastRead = opInvalid |
| 310 | if b.off >= len(b.buf) { |
| 311 | // Buffer is empty, reset to recover space. |
| 312 | b.Truncate(0) |
| 313 | return 0, 0, io.EOF |
| 314 | } |
| 315 | b.lastRead = opReadRune |
| 316 | c := b.buf[b.off] |
| 317 | if c < utf8.RuneSelf { |
| 318 | b.off++ |
| 319 | return rune(c), 1, nil |
| 320 | } |
| 321 | r, n := utf8.DecodeRune(b.buf[b.off:]) |
| 322 | b.off += n |
| 323 | return r, n, nil |
| 324 | } |
| 325 | |
| 326 | // UnreadRune unreads the last rune returned by ReadRune. |
| 327 | // If the most recent read or write operation on the buffer was |
| 328 | // not a ReadRune, UnreadRune returns an error. (In this regard |
| 329 | // it is stricter than UnreadByte, which will unread the last byte |
| 330 | // from any read operation.) |
| 331 | func (b *Buffer) UnreadRune() error { |
| 332 | if b.lastRead != opReadRune { |
| 333 | return errors.New("bytes.Buffer: UnreadRune: previous operation was not ReadRune") |
| 334 | } |
| 335 | b.lastRead = opInvalid |
| 336 | if b.off > 0 { |
| 337 | _, n := utf8.DecodeLastRune(b.buf[0:b.off]) |
| 338 | b.off -= n |
| 339 | } |
| 340 | return nil |
| 341 | } |
| 342 | |
| 343 | // UnreadByte unreads the last byte returned by the most recent |
| 344 | // read operation. If write has happened since the last read, UnreadByte |
| 345 | // returns an error. |
| 346 | func (b *Buffer) UnreadByte() error { |
| 347 | if b.lastRead != opReadRune && b.lastRead != opRead { |
| 348 | return errors.New("bytes.Buffer: UnreadByte: previous operation was not a read") |
| 349 | } |
| 350 | b.lastRead = opInvalid |
| 351 | if b.off > 0 { |
| 352 | b.off-- |
| 353 | } |
| 354 | return nil |
| 355 | } |
| 356 | |
| 357 | // ReadBytes reads until the first occurrence of delim in the input, |
| 358 | // returning a slice containing the data up to and including the delimiter. |
| 359 | // If ReadBytes encounters an error before finding a delimiter, |
| 360 | // it returns the data read before the error and the error itself (often io.EOF). |
| 361 | // ReadBytes returns err != nil if and only if the returned data does not end in |
| 362 | // delim. |
| 363 | func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) { |
| 364 | slice, err := b.readSlice(delim) |
| 365 | // return a copy of slice. The buffer's backing array may |
| 366 | // be overwritten by later calls. |
| 367 | line = append(line, slice...) |
| 368 | return |
| 369 | } |
| 370 | |
| 371 | // readSlice is like ReadBytes but returns a reference to internal buffer data. |
| 372 | func (b *Buffer) readSlice(delim byte) (line []byte, err error) { |
| 373 | i := bytes.IndexByte(b.buf[b.off:], delim) |
| 374 | end := b.off + i + 1 |
| 375 | if i < 0 { |
| 376 | end = len(b.buf) |
| 377 | err = io.EOF |
| 378 | } |
| 379 | line = b.buf[b.off:end] |
| 380 | b.off = end |
| 381 | b.lastRead = opRead |
| 382 | return line, err |
| 383 | } |
| 384 | |
| 385 | // ReadString reads until the first occurrence of delim in the input, |
| 386 | // returning a string containing the data up to and including the delimiter. |
| 387 | // If ReadString encounters an error before finding a delimiter, |
| 388 | // it returns the data read before the error and the error itself (often io.EOF). |
| 389 | // ReadString returns err != nil if and only if the returned data does not end |
| 390 | // in delim. |
| 391 | func (b *Buffer) ReadString(delim byte) (line string, err error) { |
| 392 | slice, err := b.readSlice(delim) |
| 393 | return string(slice), err |
| 394 | } |
| 395 | |
| 396 | // NewBuffer creates and initializes a new Buffer using buf as its initial |
| 397 | // contents. It is intended to prepare a Buffer to read existing data. It |
| 398 | // can also be used to size the internal buffer for writing. To do that, |
| 399 | // buf should have the desired capacity but a length of zero. |
| 400 | // |
| 401 | // In most cases, new(Buffer) (or just declaring a Buffer variable) is |
| 402 | // sufficient to initialize a Buffer. |
| 403 | func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} } |
| 404 | |
| 405 | // NewBufferString creates and initializes a new Buffer using string s as its |
| 406 | // initial contents. It is intended to prepare a buffer to read an existing |
| 407 | // string. |
| 408 | // |
| 409 | // In most cases, new(Buffer) (or just declaring a Buffer variable) is |
| 410 | // sufficient to initialize a Buffer. |
| 411 | func NewBufferString(s string) *Buffer { |
| 412 | return &Buffer{buf: []byte(s)} |
| 413 | } |