go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/iotools/countingwriter.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  // CountingWriter is an io.Writer that counts the number of bytes that are
    22  // written.
    23  type CountingWriter struct {
    24  	io.Writer // The underlying io.Writer.
    25  
    26  	// Count is the number of bytes that have been written.
    27  	Count int64
    28  
    29  	singleByteBuf [1]byte
    30  }
    31  
    32  var _ io.Writer = (*CountingWriter)(nil)
    33  
    34  // Write implements io.Writer.
    35  func (c *CountingWriter) Write(buf []byte) (int, error) {
    36  	amount, err := c.Writer.Write(buf)
    37  	c.Count += int64(amount)
    38  	return amount, err
    39  }
    40  
    41  // WriteByte implements io.ByteWriter.
    42  func (c *CountingWriter) WriteByte(b byte) error {
    43  	// If our underlying Writer is a ByteWriter, use its WriteByte directly.
    44  	if bw, ok := c.Writer.(io.ByteWriter); ok {
    45  		if err := bw.WriteByte(b); err != nil {
    46  			return err
    47  		}
    48  		c.Count++
    49  		return nil
    50  	}
    51  
    52  	c.singleByteBuf[0] = b
    53  	_, err := c.Write(c.singleByteBuf[:])
    54  	return err
    55  }