Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright 2015 The LUCI Authors. All rights reserved. | 1 // Copyright 2015 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 | 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. | 3 // that can be found in the LICENSE file. |
| 4 | 4 |
| 5 package iotools | 5 package iotools |
| 6 | 6 |
| 7 import ( | 7 import ( |
| 8 "io" | 8 "io" |
| 9 ) | 9 ) |
| 10 | 10 |
| 11 // CountingReader is an io.Reader that counts the number of bytes that are read. | 11 // CountingReader is an io.Reader that counts the number of bytes that are read. |
| 12 type CountingReader struct { | 12 type CountingReader struct { |
| 13 io.Reader // The underlying io.Reader. | 13 io.Reader // The underlying io.Reader. |
| 14 | 14 |
| 15 » count int64 | 15 » Count int64 |
|
dnj
2016/10/19 23:18:59
This is trivial enough that I don't mind combining
| |
| 16 } | 16 } |
| 17 | 17 |
| 18 var _ io.Reader = (*CountingReader)(nil) | 18 var _ io.Reader = (*CountingReader)(nil) |
| 19 | 19 |
| 20 // Read implements io.Reader. | 20 // Read implements io.Reader. |
| 21 func (c *CountingReader) Read(buf []byte) (int, error) { | 21 func (c *CountingReader) Read(buf []byte) (int, error) { |
| 22 amount, err := c.Reader.Read(buf) | 22 amount, err := c.Reader.Read(buf) |
| 23 » c.count += int64(amount) | 23 » c.Count += int64(amount) |
| 24 return amount, err | 24 return amount, err |
| 25 } | 25 } |
| 26 | 26 |
| 27 // ReadByte implements io.ByteReader. | 27 // ReadByte implements io.ByteReader. |
| 28 func (c *CountingReader) ReadByte() (byte, error) { | 28 func (c *CountingReader) ReadByte() (byte, error) { |
| 29 // If our underlying reader is a ByteReader, use its ReadByte directly. | 29 // If our underlying reader is a ByteReader, use its ReadByte directly. |
| 30 if br, ok := c.Reader.(io.ByteReader); ok { | 30 if br, ok := c.Reader.(io.ByteReader); ok { |
| 31 b, err := br.ReadByte() | 31 b, err := br.ReadByte() |
| 32 if err == nil { | 32 if err == nil { |
| 33 » » » c.count++ | 33 » » » c.Count++ |
| 34 } | 34 } |
| 35 return b, err | 35 return b, err |
| 36 } | 36 } |
| 37 | 37 |
| 38 data := []byte{0} | 38 data := []byte{0} |
| 39 amount, err := c.Reader.Read(data) | 39 amount, err := c.Reader.Read(data) |
| 40 if amount != 0 { | 40 if amount != 0 { |
| 41 » » c.count += int64(amount) | 41 » » c.Count += int64(amount) |
| 42 return data[0], err | 42 return data[0], err |
| 43 } | 43 } |
| 44 return 0, err | 44 return 0, err |
| 45 } | 45 } |
| 46 | |
| 47 // Count returns the number of bytes that have been read. | |
| 48 func (c *CountingReader) Count() int64 { | |
| 49 return c.count | |
| 50 } | |
| OLD | NEW |