go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/iotools/countingreader.go (about) 1 // Copyright 2015 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package iotools 16 17 import ( 18 "io" 19 ) 20 21 // CountingReader is an io.Reader that counts the number of bytes that are read. 22 type CountingReader struct { 23 io.Reader // The underlying io.Reader. 24 25 Count int64 26 } 27 28 var _ io.Reader = (*CountingReader)(nil) 29 30 // Read implements io.Reader. 31 func (c *CountingReader) Read(buf []byte) (int, error) { 32 amount, err := c.Reader.Read(buf) 33 c.Count += int64(amount) 34 return amount, err 35 } 36 37 // ReadByte implements io.ByteReader. 38 func (c *CountingReader) ReadByte() (byte, error) { 39 // If our underlying reader is a ByteReader, use its ReadByte directly. 40 if br, ok := c.Reader.(io.ByteReader); ok { 41 b, err := br.ReadByte() 42 if err == nil { 43 c.Count++ 44 } 45 return b, err 46 } 47 48 data := []byte{0} 49 amount, err := c.Reader.Read(data) 50 if amount != 0 { 51 c.Count += int64(amount) 52 return data[0], err 53 } 54 return 0, err 55 }