read_counter.go (719B)
1 package rifs 2 3 import ( 4 "io" 5 ) 6 7 // ReadCounter proxies read requests and maintains a counter of bytes read. 8 type ReadCounter struct { 9 r io.Reader 10 counter int 11 } 12 13 // NewReadCounter returns a new `ReadCounter` struct wrapping a `Reader`. 14 func NewReadCounter(r io.Reader) *ReadCounter { 15 return &ReadCounter{ 16 r: r, 17 } 18 } 19 20 // Count returns the total number of bytes read. 21 func (rc *ReadCounter) Count() int { 22 return rc.counter 23 } 24 25 // Reset resets the counter to zero. 26 func (rc *ReadCounter) Reset() { 27 rc.counter = 0 28 } 29 30 // Read forwards a read to the underlying `Reader` while bumping the counter. 31 func (rc *ReadCounter) Read(b []byte) (n int, err error) { 32 n, err = rc.r.Read(b) 33 rc.counter += n 34 35 return n, err 36 }