reader.go (878B)
1 package buffer 2 3 import "io" 4 5 // Reader implements an io.Reader over a byte slice. 6 type Reader struct { 7 buf []byte 8 pos int 9 } 10 11 // NewReader returns a new Reader for a given byte slice. 12 func NewReader(buf []byte) *Reader { 13 return &Reader{ 14 buf: buf, 15 } 16 } 17 18 // Read reads bytes into the given byte slice and returns the number of bytes read and an error if occurred. 19 func (r *Reader) Read(b []byte) (n int, err error) { 20 if len(b) == 0 { 21 return 0, nil 22 } 23 if r.pos >= len(r.buf) { 24 return 0, io.EOF 25 } 26 n = copy(b, r.buf[r.pos:]) 27 r.pos += n 28 return 29 } 30 31 // Bytes returns the underlying byte slice. 32 func (r *Reader) Bytes() []byte { 33 return r.buf 34 } 35 36 // Reset resets the position of the read pointer to the beginning of the underlying byte slice. 37 func (r *Reader) Reset() { 38 r.pos = 0 39 } 40 41 // Len returns the length of the buffer. 42 func (r *Reader) Len() int { 43 return len(r.buf) 44 }