src/pkg/bytes/buffer.go - The Go Programming Language

Golang

Source file src/pkg/bytes/buffer.go

     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 bytes
     6	
     7	// Simple byte buffer for marshaling data.
     8	
     9	import (
    10		"errors"
    11		"io"
    12		"unicode/utf8"
    13	)
    14	
    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.
    17	type Buffer struct {
    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.
    23	}
    24	
    25	// The readOp constants describe the last action performed on
    26	// the buffer, so that UnreadRune and UnreadByte can
    27	// check for invalid usage.
    28	type readOp int
    29	
    30	const (
    31		opInvalid  readOp = iota // Non-read operation.
    32		opReadRune               // Read rune.
    33		opRead                   // Any other read operation.
    34	)
    35	
    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")
    38	
    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:] }
    44	
    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 {
    48		if b == nil {
    49			// Special case, useful in debugging.
    50			return "<nil>"
    51		}
    52		return string(b.buf[b.off:])
    53	}
    54	
    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 }
    58	
    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
    63		switch {
    64		case n < 0 || n > b.Len():
    65			panic("bytes.Buffer: truncation out of range")
    66		case n == 0:
    67			// Reuse buffer space.
    68			b.off = 0
    69		}
    70		b.buf = b.buf[0 : b.off+n]
    71	}
    72	
    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) }
    76	
    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 {
    81		m := b.Len()
    82		// If buffer is empty, reset to recover space.
    83		if m == 0 && b.off != 0 {
    84			b.Truncate(0)
    85		}
    86		if len(b.buf)+n > cap(b.buf) {
    87			var buf []byte
    88			if b.buf == nil && n <= len(b.bootstrap) {
    89				buf = b.bootstrap[0:]
    90			} else {
    91				// not enough space anywhere
    92				buf = makeSlice(2*cap(b.buf) + n)
    93				copy(buf, b.buf[b.off:])
    94			}
    95			b.buf = buf
    96			b.off = 0
    97		}
    98		b.buf = b.buf[0 : b.off+m+n]
    99		return b.off + m
   100	}
   101	
   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
   105	// ErrTooLarge.
   106	func (b *Buffer) Write(p []byte) (n int, err error) {
   107		b.lastRead = opInvalid
   108		m := b.grow(len(p))
   109		return copy(b.buf[m:], p), nil
   110	}
   111	
   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
   115	// ErrTooLarge.
   116	func (b *Buffer) WriteString(s string) (n int, err error) {
   117		b.lastRead = opInvalid
   118		m := b.grow(len(s))
   119		return copy(b.buf[m:], s), nil
   120	}
   121	
   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.
   126	const MinRead = 512
   127	
   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
   131	// is also returned.
   132	// If the buffer becomes too large, ReadFrom will panic with
   133	// ErrTooLarge.
   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) {
   138			b.Truncate(0)
   139		}
   140		for {
   141			if free := cap(b.buf) - len(b.buf); free < MinRead {
   142				// not enough space at end
   143				newBuf := b.buf
   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)
   148				}
   149				copy(newBuf, b.buf[b.off:])
   150				b.buf = newBuf[:len(b.buf)-b.off]
   151				b.off = 0
   152			}
   153			m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
   154			b.buf = b.buf[0 : len(b.buf)+m]
   155			n += int64(m)
   156			if e == io.EOF {
   157				break
   158			}
   159			if e != nil {
   160				return n, e
   161			}
   162		}
   163		return n, nil // err is EOF, so return nil explicitly
   164	}
   165	
   166	// makeSlice allocates a slice of size n. If the allocation fails, it panics
   167	// with ErrTooLarge.
   168	func makeSlice(n int) []byte {
   169		// If the make fails, give a known error.
   170		defer func() {
   171			if recover() != nil {
   172				panic(ErrTooLarge)
   173			}
   174		}()
   175		return make([]byte, n)
   176	}
   177	
   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) {
   185			nBytes := b.Len()
   186			m, e := w.Write(b.buf[b.off:])
   187			if m > nBytes {
   188				panic("bytes.Buffer.WriteTo: invalid Write count")
   189			}
   190			b.off += m
   191			n = int64(m)
   192			if e != nil {
   193				return n, e
   194			}
   195			// all bytes should have been written, by definition of
   196			// Write method in io.Writer
   197			if m != nBytes {
   198				return n, io.ErrShortWrite
   199			}
   200		}
   201		// Buffer is now empty; reset.
   202		b.Truncate(0)
   203		return
   204	}
   205	
   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
   210	// ErrTooLarge.
   211	func (b *Buffer) WriteByte(c byte) error {
   212		b.lastRead = opInvalid
   213		m := b.grow(1)
   214		b.buf[m] = c
   215		return nil
   216	}
   217	
   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
   223	// ErrTooLarge.
   224	func (b *Buffer) WriteRune(r rune) (n int, err error) {
   225		if r < utf8.RuneSelf {
   226			b.WriteByte(byte(r))
   227			return 1, nil
   228		}
   229		n = utf8.EncodeRune(b.runeBytes[0:], r)
   230		b.Write(b.runeBytes[0:n])
   231		return n, nil
   232	}
   233	
   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.
   242			b.Truncate(0)
   243			if len(p) == 0 {
   244				return
   245			}
   246			return 0, io.EOF
   247		}
   248		n = copy(p, b.buf[b.off:])
   249		b.off += n
   250		if n > 0 {
   251			b.lastRead = opRead
   252		}
   253		return
   254	}
   255	
   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
   262		m := b.Len()
   263		if n > m {
   264			n = m
   265		}
   266		data := b.buf[b.off : b.off+n]
   267		b.off += n
   268		if n > 0 {
   269			b.lastRead = opRead
   270		}
   271		return data
   272	}
   273	
   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.
   280			b.Truncate(0)
   281			return 0, io.EOF
   282		}
   283		c = b.buf[b.off]
   284		b.off++
   285		b.lastRead = opRead
   286		return c, nil
   287	}
   288	
   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.
   298			b.Truncate(0)
   299			return 0, 0, io.EOF
   300		}
   301		b.lastRead = opReadRune
   302		c := b.buf[b.off]
   303		if c < utf8.RuneSelf {
   304			b.off++
   305			return rune(c), 1, nil
   306		}
   307		r, n := utf8.DecodeRune(b.buf[b.off:])
   308		b.off += n
   309		return r, n, nil
   310	}
   311	
   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")
   320		}
   321		b.lastRead = opInvalid
   322		if b.off > 0 {
   323			_, n := utf8.DecodeLastRune(b.buf[0:b.off])
   324			b.off -= n
   325		}
   326		return nil
   327	}
   328	
   329	// UnreadByte unreads the last byte returned by the most recent
   330	// read operation.  If write has happened since the last read, UnreadByte
   331	// returns an error.
   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")
   335		}
   336		b.lastRead = opInvalid
   337		if b.off > 0 {
   338			b.off--
   339		}
   340		return nil
   341	}
   342	
   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
   348	// delim.
   349	func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
   350		i := IndexByte(b.buf[b.off:], delim)
   351		size := i + 1
   352		if i < 0 {
   353			size = len(b.buf) - b.off
   354			err = io.EOF
   355		}
   356		line = make([]byte, size)
   357		copy(line, b.buf[b.off:])
   358		b.off += size
   359		return
   360	}
   361	
   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
   367	// in delim.
   368	func (b *Buffer) ReadString(delim byte) (line string, err error) {
   369		bytes, err := b.ReadBytes(delim)
   370		return string(bytes), err
   371	}
   372	
   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.
   377	//
   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} }
   381	
   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
   384	// string.
   385	//
   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)}
   390	}