...

Source file src/github.com/dsoprea/go-utility/v2/crypto/reader_hash_proxy.go

Documentation: github.com/dsoprea/go-utility/v2/crypto

     1  package ricrypto
     2  
     3  import (
     4  	"hash"
     5  	"io"
     6  
     7  	"github.com/dsoprea/go-logging"
     8  )
     9  
    10  // ReaderHashProxy proxies a reader and produces a `Hash` sum from the read
    11  // bytes.
    12  type ReaderHashProxy struct {
    13  	r io.Reader
    14  	h hash.Hash
    15  }
    16  
    17  // NewReaderHashProxy returns a new `ReaderHashProxy` struct.
    18  func NewReaderHashProxy(r io.Reader, h hash.Hash) *ReaderHashProxy {
    19  	return &ReaderHashProxy{
    20  		r: r,
    21  		h: h,
    22  	}
    23  }
    24  
    25  // Read proxies the read to the underlying `Reader` while also pushing the bytes
    26  // through the `Hash` struct.
    27  func (rhp *ReaderHashProxy) Read(b []byte) (n int, err error) {
    28  	defer func() {
    29  		if state := recover(); state != nil {
    30  			err = log.Wrap(state.(error))
    31  		}
    32  	}()
    33  
    34  	n, err = rhp.r.Read(b)
    35  	if err != nil {
    36  		if err == io.EOF {
    37  			return 0, err
    38  		}
    39  
    40  		log.Panic(err)
    41  	}
    42  
    43  	n, err = rhp.h.Write(b[:n])
    44  	log.PanicIf(err)
    45  
    46  	return n, nil
    47  }
    48  
    49  // Sum returns the accumulated hash value.
    50  func (rhp *ReaderHashProxy) Sum() []byte {
    51  	return rhp.h.Sum(nil)
    52  }
    53  
    54  // ReaderHash32Proxy proxies a reader and produces a `Hash32` sum from the read
    55  // bytes.
    56  type ReaderHash32Proxy struct {
    57  	r io.Reader
    58  	h hash.Hash32
    59  }
    60  
    61  // NewReaderHash32Proxy returns a new `ReaderHash32Proxy` struct.
    62  func NewReaderHash32Proxy(r io.Reader, h hash.Hash32) *ReaderHash32Proxy {
    63  	return &ReaderHash32Proxy{
    64  		r: r,
    65  		h: h,
    66  	}
    67  }
    68  
    69  // Read proxies the read to the underlying `Reader` while also pushing the bytes
    70  // through the `Hash32` struct.
    71  func (rhp *ReaderHash32Proxy) Read(b []byte) (n int, err error) {
    72  	defer func() {
    73  		if state := recover(); state != nil {
    74  			err = log.Wrap(state.(error))
    75  		}
    76  	}()
    77  
    78  	n, err = rhp.r.Read(b)
    79  	if err != nil {
    80  		if err == io.EOF {
    81  			return 0, err
    82  		}
    83  
    84  		log.Panic(err)
    85  	}
    86  
    87  	n, err = rhp.h.Write(b[:n])
    88  	log.PanicIf(err)
    89  
    90  	return n, nil
    91  }
    92  
    93  // Sum32 returns the accumulated hash value.
    94  func (rhp *ReaderHash32Proxy) Sum32() uint32 {
    95  	return rhp.h.Sum32()
    96  }
    97  

View as plain text