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

     1  package binary
     2  
     3  import (
     4  	"github.com/webmafia/fast"
     5  )
     6  
     7  var _ Reader = (*BufferReader)(nil)
     8  
     9  type BufferReader struct {
    10  	buf    []byte
    11  	cursor int
    12  }
    13  
    14  func NewBufferReader(buf []byte) *BufferReader {
    15  	return &BufferReader{
    16  		buf: buf,
    17  	}
    18  }
    19  
    20  func (b *BufferReader) Len() int {
    21  	return b.Cap() - b.cursor
    22  }
    23  
    24  func (b *BufferReader) Cap() int {
    25  	return len(b.buf)
    26  }
    27  
    28  func (b *BufferReader) Reset() {
    29  	b.cursor = 0
    30  }
    31  
    32  func (b *BufferReader) Read(dst []byte) (n int, err error) {
    33  	n = copy(dst, b.buf[b.cursor:])
    34  	b.cursor += n
    35  	return
    36  }
    37  
    38  func (b *BufferReader) ReadByte() (byte, error) {
    39  	v := b.buf[b.cursor]
    40  	b.cursor++
    41  	return v, nil
    42  }
    43  
    44  func (b *BufferReader) ReadBytes(n int) (dst []byte) {
    45  	dst = b.buf[b.cursor : b.cursor+n]
    46  	b.cursor += n
    47  	return
    48  }
    49  
    50  func (b *BufferReader) ReadString(n int) string {
    51  	return fast.BytesToString(b.ReadBytes(n))
    52  }