github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/io/binaryBufWriter.go (about)

     1  package io
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  )
     7  
     8  // ErrDrained is returned on an attempt to use an already drained write buffer.
     9  var ErrDrained = errors.New("buffer already drained")
    10  
    11  // BufBinWriter is an additional layer on top of BinWriter that
    12  // automatically creates a buffer to write into that you can get after all
    13  // writes via Bytes().
    14  type BufBinWriter struct {
    15  	*BinWriter
    16  	buf bytes.Buffer
    17  }
    18  
    19  // NewBufBinWriter makes a BufBinWriter with an empty byte buffer.
    20  func NewBufBinWriter() *BufBinWriter {
    21  	b := new(BufBinWriter)
    22  	b.BinWriter = NewBinWriterFromIO(&b.buf)
    23  	return b
    24  }
    25  
    26  // Len returns the number of bytes of the unread portion of the buffer.
    27  func (bw *BufBinWriter) Len() int {
    28  	return bw.buf.Len()
    29  }
    30  
    31  // Bytes returns the resulting buffer and makes future writes return an error.
    32  func (bw *BufBinWriter) Bytes() []byte {
    33  	if bw.Err != nil {
    34  		return nil
    35  	}
    36  	bw.Err = ErrDrained
    37  	return bw.buf.Bytes()
    38  }
    39  
    40  // Reset resets the state of the buffer, making it usable again. It can
    41  // make buffer usage somewhat more efficient because you don't need to
    42  // create it again. But beware, the buffer is gonna be the same as the one
    43  // returned by Bytes(), so if you need that data after Reset() you have to copy
    44  // it yourself.
    45  func (bw *BufBinWriter) Reset() {
    46  	bw.Err = nil
    47  	bw.buf.Reset()
    48  }