github.com/scottcagno/storage@v1.8.0/pkg/_bio/buffer/buffer.go (about)

     1  package buffer
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"io"
     7  	"runtime"
     8  	"unicode/utf8"
     9  )
    10  
    11  // smallBufferSize is an initial allocation minimal capacity.
    12  const smallBufferSize = 64
    13  
    14  // A Buffer is a variable-sized buffer of bytes with Read and Write methods.
    15  // The zero value for Buffer is an empty buffer ready to use.
    16  type Buffer struct {
    17  	buf      []byte // contents are the bytes buf[off : len(buf)]
    18  	off      int    // read at &buf[off], write at &buf[len(buf)]
    19  	lastRead readOp // last read operation, so that Unread* can work correctly.
    20  }
    21  
    22  // The readOp constants describe the last action performed on
    23  // the buffer, so that UnreadRune and UnreadByte can check for
    24  // invalid usage. opReadRuneX constants are chosen such that
    25  // converted to int they correspond to the rune size that was read.
    26  type readOp int8
    27  
    28  // Don't use iota for these, as the values need to correspond with the
    29  // names and comments, which is easier to see when being explicit.
    30  const (
    31  	opRead      readOp = -1 // Any other read operation.
    32  	opInvalid   readOp = 0  // Non-read operation.
    33  	opReadRune1 readOp = 1  // Read rune of size 1.
    34  	opReadRune2 readOp = 2  // Read rune of size 2.
    35  	opReadRune3 readOp = 3  // Read rune of size 3.
    36  	opReadRune4 readOp = 4  // Read rune of size 4.
    37  )
    38  
    39  // ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
    40  var ErrTooLarge = errors.New("bytes.Buffer: too large")
    41  var errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read")
    42  
    43  const maxInt = int(^uint(0) >> 1)
    44  
    45  // Bytes returns a slice of length b.Len() holding the unread portion of the buffer.
    46  // The slice is valid for use only until the next buffer modification (that is,
    47  // only until the next call to a method like Read, Write, Reset, or Truncate).
    48  // The slice aliases the buffer content at least until the next buffer modification,
    49  // so immediate changes to the slice will affect the result of future reads.
    50  func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
    51  
    52  // String returns the contents of the unread portion of the buffer
    53  // as a string. If the Buffer is a nil pointer, it returns "<nil>".
    54  //
    55  // To build strings more efficiently, see the strings.Builder type.
    56  func (b *Buffer) String() string {
    57  	if b == nil {
    58  		// Special case, useful in debugging.
    59  		return "<nil>"
    60  	}
    61  	return string(b.buf[b.off:])
    62  }
    63  
    64  // empty reports whether the unread portion of the buffer is empty.
    65  func (b *Buffer) empty() bool { return len(b.buf) <= b.off }
    66  
    67  // Len returns the number of bytes of the unread portion of the buffer;
    68  // b.Len() == len(b.Bytes()).
    69  func (b *Buffer) Len() int { return len(b.buf) - b.off }
    70  
    71  // Cap returns the capacity of the buffer's underlying byte slice, that is, the
    72  // total space allocated for the buffer's data.
    73  func (b *Buffer) Cap() int { return cap(b.buf) }
    74  
    75  // Truncate discards all but the first n unread bytes from the buffer
    76  // but continues to use the same allocated storage.
    77  // It panics if n is negative or greater than the length of the buffer.
    78  func (b *Buffer) Truncate(n int) {
    79  	if n == 0 {
    80  		b.Reset()
    81  		return
    82  	}
    83  	b.lastRead = opInvalid
    84  	if n < 0 || n > b.Len() {
    85  		panic("bytes.Buffer: truncation out of range")
    86  	}
    87  	b.buf = b.buf[:b.off+n]
    88  }
    89  
    90  // Reset resets the buffer to be empty,
    91  // but it retains the underlying storage for use by future writes.
    92  // Reset is the same as Truncate(0).
    93  func (b *Buffer) Reset() {
    94  	b.buf = b.buf[:0]
    95  	b.off = 0
    96  	b.lastRead = opInvalid
    97  }
    98  
    99  // Free resets the buffer to be empty,
   100  // but it DOES NOT retain the underlying storage for use by future writes.
   101  func (b *Buffer) Free() {
   102  	b.buf = nil
   103  	b.off = 0
   104  	b.lastRead = opInvalid
   105  	runtime.GC()
   106  }
   107  
   108  // tryGrowByReslice is a inlineable version of grow for the fast-case where the
   109  // internal buffer only needs to be resliced.
   110  // It returns the index where bytes should be written and whether it succeeded.
   111  func (b *Buffer) tryGrowByReslice(n int) (int, bool) {
   112  	if l := len(b.buf); n <= cap(b.buf)-l {
   113  		b.buf = b.buf[:l+n]
   114  		return l, true
   115  	}
   116  	return 0, false
   117  }
   118  
   119  // grow grows the buffer to guarantee space for n more bytes.
   120  // It returns the index where bytes should be written.
   121  // If the buffer can't grow it will panic with ErrTooLarge.
   122  func (b *Buffer) grow(n int) int {
   123  	m := b.Len()
   124  	// If buffer is empty, reset to recover space.
   125  	if m == 0 && b.off != 0 {
   126  		b.Reset()
   127  	}
   128  	// Try to grow by means of a reslice.
   129  	if i, ok := b.tryGrowByReslice(n); ok {
   130  		return i
   131  	}
   132  	if b.buf == nil && n <= smallBufferSize {
   133  		b.buf = make([]byte, n, smallBufferSize)
   134  		return 0
   135  	}
   136  	c := cap(b.buf)
   137  	if n <= c/2-m {
   138  		// We can slide things down instead of allocating a new
   139  		// slice. We only need m+n <= c to slide, but
   140  		// we instead let capacity get twice as large so we
   141  		// don't spend all our time copying.
   142  		copy(b.buf, b.buf[b.off:])
   143  	} else if c > maxInt-c-n {
   144  		panic(ErrTooLarge)
   145  	} else {
   146  		// Not enough space anywhere, we need to allocate.
   147  		buf := makeSlice(2*c + n)
   148  		copy(buf, b.buf[b.off:])
   149  		b.buf = buf
   150  	}
   151  	// Restore b.off and len(b.buf).
   152  	b.off = 0
   153  	b.buf = b.buf[:m+n]
   154  	return m
   155  }
   156  
   157  // Grow grows the buffer's capacity, if necessary, to guarantee space for
   158  // another n bytes. After Grow(n), at least n bytes can be written to the
   159  // buffer without another allocation.
   160  // If n is negative, Grow will panic.
   161  // If the buffer can't grow it will panic with ErrTooLarge.
   162  func (b *Buffer) Grow(n int) {
   163  	if n < 0 {
   164  		panic("bytes.Buffer.Grow: negative count")
   165  	}
   166  	m := b.grow(n)
   167  	b.buf = b.buf[:m]
   168  }
   169  
   170  // Write appends the contents of p to the buffer, growing the buffer as
   171  // needed. The return value n is the length of p; err is always nil. If the
   172  // buffer becomes too large, Write will panic with ErrTooLarge.
   173  func (b *Buffer) Write(p []byte) (n int, err error) {
   174  	b.lastRead = opInvalid
   175  	m, ok := b.tryGrowByReslice(len(p))
   176  	if !ok {
   177  		m = b.grow(len(p))
   178  	}
   179  	return copy(b.buf[m:], p), nil
   180  }
   181  
   182  func (b *Buffer) WriteAt(p []byte, off int64) (n int, err error) {
   183  	b.lastRead = opInvalid
   184  	var cur int
   185  	cur = b.off
   186  	m, ok := b.tryGrowByReslice(len(p) + int(off))
   187  	if !ok {
   188  		m = b.grow(len(p) + int(off))
   189  	}
   190  	n = copy(b.buf[m:], p)
   191  	b.off = cur
   192  	return n, nil
   193  }
   194  
   195  // makeSlice allocates a slice of size n. If the allocation fails, it panics
   196  // with ErrTooLarge.
   197  func makeSlice(n int) []byte {
   198  	// If the make fails, give a known error.
   199  	defer func() {
   200  		if recover() != nil {
   201  			panic(ErrTooLarge)
   202  		}
   203  	}()
   204  	return make([]byte, n)
   205  }
   206  
   207  // WriteByte appends the byte c to the buffer, growing the buffer as needed.
   208  // The returned error is always nil, but is included to match bufio.Writer's
   209  // WriteByte. 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, ok := b.tryGrowByReslice(1)
   214  	if !ok {
   215  		m = b.grow(1)
   216  	}
   217  	b.buf[m] = c
   218  	return nil
   219  }
   220  
   221  // WriteRune appends the UTF-8 encoding of Unicode code point r to the
   222  // buffer, returning its length and an error, which is always nil but is
   223  // included to match bufio.Writer's WriteRune. The buffer is grown as needed;
   224  // if it becomes too large, WriteRune will panic with ErrTooLarge.
   225  func (b *Buffer) WriteRune(r rune) (n int, err error) {
   226  	// Compare as uint32 to correctly handle negative runes.
   227  	if uint32(r) < utf8.RuneSelf {
   228  		b.WriteByte(byte(r))
   229  		return 1, nil
   230  	}
   231  	b.lastRead = opInvalid
   232  	m, ok := b.tryGrowByReslice(utf8.UTFMax)
   233  	if !ok {
   234  		m = b.grow(utf8.UTFMax)
   235  	}
   236  	n = utf8.EncodeRune(b.buf[m:m+utf8.UTFMax], r)
   237  	b.buf = b.buf[:m+n]
   238  	return n, nil
   239  }
   240  
   241  // Read reads the next len(p) bytes from the buffer or until the buffer
   242  // is drained. The return value n is the number of bytes read. If the
   243  // buffer has no data to return, err is io.EOF (unless len(p) is zero);
   244  // otherwise it is nil.
   245  func (b *Buffer) Read(p []byte) (n int, err error) {
   246  	b.lastRead = opInvalid
   247  	if b.empty() {
   248  		// Buffer is empty, reset to recover space.
   249  		b.Reset()
   250  		if len(p) == 0 {
   251  			return 0, nil
   252  		}
   253  		return 0, io.EOF
   254  	}
   255  	n = copy(p, b.buf[b.off:])
   256  	b.off += n
   257  	if n > 0 {
   258  		b.lastRead = opRead
   259  	}
   260  	return n, nil
   261  }
   262  
   263  func (b *Buffer) ReadAt(p []byte, off int64) (n int, err error) {
   264  	b.lastRead = opInvalid
   265  	if int(off) > b.Cap() {
   266  		return 0, io.EOF
   267  	}
   268  	var cur int
   269  	cur = b.off
   270  	if b.empty() {
   271  		// Buffer is empty, reset to recover space.
   272  		b.Reset()
   273  		if len(p) == 0 {
   274  			return 0, nil
   275  		}
   276  		return 0, io.EOF
   277  	}
   278  	n = copy(p, b.buf[b.off:])
   279  	b.off += n
   280  	if n > 0 {
   281  		b.lastRead = opRead
   282  	}
   283  	b.off = cur
   284  	return n, nil
   285  }
   286  
   287  var ErrWhence = errors.New("Seek: invalid whence")
   288  var ErrOffset = errors.New("Seek: invalid offset")
   289  
   290  func (b *Buffer) Seek(offset int64, whence int) (int64, error) {
   291  	switch whence {
   292  	default:
   293  		return 0, ErrWhence
   294  	case io.SeekStart:
   295  		offset += 0
   296  	case io.SeekCurrent:
   297  		offset += int64(b.off)
   298  	case io.SeekEnd:
   299  		offset += int64(b.Cap())
   300  	}
   301  	if offset < 0 {
   302  		return 0, ErrOffset
   303  	}
   304  	b.off = int(offset)
   305  	return offset, nil
   306  }
   307  
   308  // Next returns a slice containing the next n bytes from the buffer,
   309  // advancing the buffer as if the bytes had been returned by Read.
   310  // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
   311  // The slice is only valid until the next call to a read or write method.
   312  func (b *Buffer) Next(n int) []byte {
   313  	b.lastRead = opInvalid
   314  	m := b.Len()
   315  	if n > m {
   316  		n = m
   317  	}
   318  	data := b.buf[b.off : b.off+n]
   319  	b.off += n
   320  	if n > 0 {
   321  		b.lastRead = opRead
   322  	}
   323  	return data
   324  }
   325  
   326  // ReadByte reads and returns the next byte from the buffer.
   327  // If no byte is available, it returns error io.EOF.
   328  func (b *Buffer) ReadByte() (byte, error) {
   329  	if b.empty() {
   330  		// Buffer is empty, reset to recover space.
   331  		b.Reset()
   332  		return 0, io.EOF
   333  	}
   334  	c := b.buf[b.off]
   335  	b.off++
   336  	b.lastRead = opRead
   337  	return c, nil
   338  }
   339  
   340  // ReadRune reads and returns the next UTF-8-encoded
   341  // Unicode code point from the buffer.
   342  // If no bytes are available, the error returned is io.EOF.
   343  // If the bytes are an erroneous UTF-8 encoding, it
   344  // consumes one byte and returns U+FFFD, 1.
   345  func (b *Buffer) ReadRune() (r rune, size int, err error) {
   346  	if b.empty() {
   347  		// Buffer is empty, reset to recover space.
   348  		b.Reset()
   349  		return 0, 0, io.EOF
   350  	}
   351  	c := b.buf[b.off]
   352  	if c < utf8.RuneSelf {
   353  		b.off++
   354  		b.lastRead = opReadRune1
   355  		return rune(c), 1, nil
   356  	}
   357  	r, n := utf8.DecodeRune(b.buf[b.off:])
   358  	b.off += n
   359  	b.lastRead = readOp(n)
   360  	return r, n, nil
   361  }
   362  
   363  // UnreadRune unreads the last rune returned by ReadRune.
   364  // If the most recent read or write operation on the buffer was
   365  // not a successful ReadRune, UnreadRune returns an error.  (In this regard
   366  // it is stricter than UnreadByte, which will unread the last byte
   367  // from any read operation.)
   368  func (b *Buffer) UnreadRune() error {
   369  	if b.lastRead <= opInvalid {
   370  		return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune")
   371  	}
   372  	if b.off >= int(b.lastRead) {
   373  		b.off -= int(b.lastRead)
   374  	}
   375  	b.lastRead = opInvalid
   376  	return nil
   377  }
   378  
   379  var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read")
   380  
   381  // UnreadByte unreads the last byte returned by the most recent successful
   382  // read operation that read at least one byte. If a write has happened since
   383  // the last read, if the last read returned an error, or if the read read zero
   384  // bytes, UnreadByte returns an error.
   385  func (b *Buffer) UnreadByte() error {
   386  	if b.lastRead == opInvalid {
   387  		return errUnreadByte
   388  	}
   389  	b.lastRead = opInvalid
   390  	if b.off > 0 {
   391  		b.off--
   392  	}
   393  	return nil
   394  }
   395  
   396  // ReadBytes reads until the first occurrence of delim in the input,
   397  // returning a slice containing the data up to and including the delimiter.
   398  // If ReadBytes encounters an error before finding a delimiter,
   399  // it returns the data read before the error and the error itself (often io.EOF).
   400  // ReadBytes returns err != nil if and only if the returned data does not end in
   401  // delim.
   402  func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
   403  	slice, err := b.readSlice(delim)
   404  	// return a copy of slice. The buffer's backing array may
   405  	// be overwritten by later calls.
   406  	line = append(line, slice...)
   407  	return line, err
   408  }
   409  
   410  // readSlice is like ReadBytes but returns a reference to internal buffer data.
   411  func (b *Buffer) readSlice(delim byte) (line []byte, err error) {
   412  	i := bytes.IndexByte(b.buf[b.off:], delim)
   413  	end := b.off + i + 1
   414  	if i < 0 {
   415  		end = len(b.buf)
   416  		err = io.EOF
   417  	}
   418  	line = b.buf[b.off:end]
   419  	b.off = end
   420  	b.lastRead = opRead
   421  	return line, err
   422  }
   423  
   424  // ReadString reads until the first occurrence of delim in the input,
   425  // returning a string containing the data up to and including the delimiter.
   426  // If ReadString encounters an error before finding a delimiter,
   427  // it returns the data read before the error and the error itself (often io.EOF).
   428  // ReadString returns err != nil if and only if the returned data does not end
   429  // in delim.
   430  func (b *Buffer) ReadString(delim byte) (line string, err error) {
   431  	slice, err := b.readSlice(delim)
   432  	return string(slice), err
   433  }
   434  
   435  // NewBuffer creates and initializes a new Buffer using buf as its
   436  // initial contents. The new Buffer takes ownership of buf, and the
   437  // caller should not use buf after this call. NewBuffer is intended to
   438  // prepare a Buffer to read existing data. It can also be used to set
   439  // the initial size of the internal buffer for writing. To do that,
   440  // buf should have the desired capacity but a length of zero.
   441  //
   442  // In most cases, new(Buffer) (or just declaring a Buffer variable) is
   443  // sufficient to initialize a Buffer.
   444  func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
   445  
   446  // NewBufferString creates and initializes a new Buffer using string s as its
   447  // initial contents. It is intended to prepare a buffer to read an existing
   448  // string.
   449  //
   450  // In most cases, new(Buffer) (or just declaring a Buffer variable) is
   451  // sufficient to initialize a Buffer.
   452  func NewBufferString(s string) *Buffer {
   453  	return &Buffer{buf: []byte(s)}
   454  }