go4.org@v0.0.0-20230225012048-214862532bf5/readerutil/readerutil.go (about)

     1  /*
     2  Copyright 2016 The go4 Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package readerutil contains io.Reader types.
    18  package readerutil // import "go4.org/readerutil"
    19  
    20  import (
    21  	"expvar"
    22  	"io"
    23  )
    24  
    25  // A SizeReaderAt is a ReaderAt with a Size method.
    26  //
    27  // An io.SectionReader implements SizeReaderAt.
    28  type SizeReaderAt interface {
    29  	Size() int64
    30  	io.ReaderAt
    31  }
    32  
    33  // A ReadSeekCloser can Read, Seek, and Close.
    34  type ReadSeekCloser interface {
    35  	io.Reader
    36  	io.Seeker
    37  	io.Closer
    38  }
    39  
    40  type ReaderAtCloser interface {
    41  	io.ReaderAt
    42  	io.Closer
    43  }
    44  
    45  // TODO(wathiede): make sure all the stat readers work with code that
    46  // type asserts ReadFrom/WriteTo.
    47  
    48  type varStatReader struct {
    49  	*expvar.Int
    50  	r io.Reader
    51  }
    52  
    53  // NewStatsReader returns an io.Reader that will have the number of bytes
    54  // read from r added to v.
    55  func NewStatsReader(v *expvar.Int, r io.Reader) io.Reader {
    56  	return &varStatReader{v, r}
    57  }
    58  
    59  func (v *varStatReader) Read(p []byte) (int, error) {
    60  	n, err := v.r.Read(p)
    61  	v.Int.Add(int64(n))
    62  	return n, err
    63  }
    64  
    65  type varStatReadSeeker struct {
    66  	*expvar.Int
    67  	rs io.ReadSeeker
    68  }
    69  
    70  // NewStatsReadSeeker returns an io.ReadSeeker that will have the number of bytes
    71  // read from rs added to v.
    72  func NewStatsReadSeeker(v *expvar.Int, rs io.ReadSeeker) io.ReadSeeker {
    73  	return &varStatReadSeeker{v, rs}
    74  }
    75  
    76  func (v *varStatReadSeeker) Read(p []byte) (int, error) {
    77  	n, err := v.rs.Read(p)
    78  	v.Int.Add(int64(n))
    79  	return n, err
    80  }
    81  
    82  func (v *varStatReadSeeker) Seek(offset int64, whence int) (int64, error) {
    83  	return v.rs.Seek(offset, whence)
    84  }