counting_reader.go 716 B

1234567891011121314151617181920212223242526272829
  1. package readers
  2. import "io"
  3. // NewCountingReader returns a CountingReader, which will read from the given
  4. // reader while keeping track of how many bytes were read.
  5. func NewCountingReader(in io.Reader) *CountingReader {
  6. return &CountingReader{in: in}
  7. }
  8. // CountingReader holds a reader and a read count of how many bytes were read
  9. // so far.
  10. type CountingReader struct {
  11. in io.Reader
  12. read uint64
  13. }
  14. // Read reads from the underlying reader.
  15. func (cr *CountingReader) Read(b []byte) (int, error) {
  16. n, err := cr.in.Read(b)
  17. cr.read += uint64(n)
  18. return n, err
  19. }
  20. // BytesRead returns how many bytes were read from the underlying reader so far.
  21. func (cr *CountingReader) BytesRead() uint64 {
  22. return cr.read
  23. }