github.com/webmafia/fast@v0.10.0/binary/stream_read.go (about)

     1  package binary
     2  
     3  import (
     4  	"bufio"
     5  	"io"
     6  
     7  	"github.com/webmafia/fast"
     8  )
     9  
    10  var _ Reader = (*StreamReader)(nil)
    11  
    12  // A StreamReader is used to efficiently read binary data from
    13  // an io.Reader.
    14  type StreamReader struct {
    15  	buf *bufio.Reader
    16  	err error
    17  }
    18  
    19  func NewStreamReader(r io.Reader) *StreamReader {
    20  	return &StreamReader{
    21  		buf: bufio.NewReader(r),
    22  	}
    23  }
    24  
    25  func (b *StreamReader) Error() error {
    26  	return b.err
    27  }
    28  
    29  // Len returns the number of accumulated bytes; b.Len() == len(b.String()).
    30  func (b *StreamReader) Len() int {
    31  	return b.buf.Buffered()
    32  }
    33  
    34  // Cap returns the capacity of the StreamReader's underlying byte slice. It is the
    35  // total space allocated for the string being built and includes any bytes
    36  // already written.
    37  func (b *StreamReader) Cap() int {
    38  	return b.buf.Size()
    39  }
    40  
    41  // Reset resets the StreamReader to be empty.
    42  func (b *StreamReader) Reset(r io.Reader) {
    43  	b.buf.Reset(r)
    44  }
    45  
    46  // Write appends the contents of p to b's buffer.
    47  // Write always returns len(p), nil.
    48  func (b *StreamReader) Read(dst []byte) (n int, err error) {
    49  	return b.buf.Read(dst)
    50  }
    51  
    52  func (b *StreamReader) ReadFull(dst []byte) (err error) {
    53  	var n int
    54  	l := len(dst)
    55  
    56  	for n < l && err == nil {
    57  		var nn int
    58  		nn, err = b.buf.Read(dst[n:])
    59  		n += nn
    60  	}
    61  
    62  	if n >= l {
    63  		err = nil
    64  	} else if n > 0 && err == io.EOF {
    65  		err = io.ErrUnexpectedEOF
    66  	}
    67  
    68  	return
    69  }
    70  
    71  // WriteByte appends the byte c to b's buffer.
    72  // The returned error is always nil.
    73  func (b *StreamReader) ReadByte() (byte, error) {
    74  	return b.buf.ReadByte()
    75  }
    76  
    77  // WriteString appends the contents of s to b's buffer.
    78  // It returns the length of s and a nil error.
    79  func (b *StreamReader) ReadBytes(n int) []byte {
    80  	buf := make([]byte, n)
    81  	n, _ = b.buf.Read(buf)
    82  	return buf[:n]
    83  }
    84  
    85  // WriteString appends the contents of s to b's buffer.
    86  // It returns the length of s and a nil error.
    87  func (b *StreamReader) ReadString(n int) string {
    88  	return fast.BytesToString(b.ReadBytes(n))
    89  }
    90  
    91  func (b *StreamReader) WriteTo(w io.Writer) (n int64, err error) {
    92  	return b.buf.WriteTo(w)
    93  }