Skip to content

Commit

Permalink
io.Copy(io.Discard, h.reader) is a bit too lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
hilmarf committed Apr 29, 2024
1 parent bb572c4 commit 72fa77a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
17 changes: 15 additions & 2 deletions pkg/iotools/hashReaderWriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,21 @@ func (h *HashReader) ReadAll() ([]byte, error) {
return io.ReadAll(h.reader)
}

// CalcHashes returns the total number of bytes read and an error if any besides EOF.
func (h *HashReader) CalcHashes() (int64, error) {
return io.Copy(io.Discard, h.reader)
b := make([]byte, 0, 512)
cnt := int64(0)
for {
n, err := h.Read(b[0:cap(b)]) // read a chunk, always from the beginning
b = b[:n] // reset slice to the actual read bytes
cnt += int64(n)
if err != nil {
if err == io.EOF {

Check failure on line 58 in pkg/iotools/hashReaderWriter.go

View workflow job for this annotation

GitHub Actions / Lint

comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint)
err = nil
}
return cnt, err
}
}
}

////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -106,7 +119,7 @@ func getBytes(h hashes, algorithm crypto.Hash) []byte {

func httpHeader(h hashes) map[string]string {
headers := make(map[string]string, len(h.hashes()))
for algorithm, _ := range h.hashes() {
for algorithm := range h.hashes() {
headers[headerName(algorithm)] = getString(h, algorithm)
}
return headers
Expand Down
9 changes: 7 additions & 2 deletions pkg/iotools/hashReaderWriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
)

var _ = Describe("Hash Reader Writer tests", func() {

It("Ensure interface implementation", func() {
var _ io.Reader = &iotools.HashReader{}
var _ io.Reader = (*iotools.HashReader)(nil)
Expand Down Expand Up @@ -62,6 +61,13 @@ var _ = Describe("Hash Reader Writer tests", func() {
Expect(hr.GetBytes(0)).To(BeNil())
Expect(hr.GetString(crypto.SHA1)).To(Equal("5c075ed604db0adc524edd3516e8f0258ca6e58d"))

hr = iotools.NewHashReader(strings.NewReader(s), crypto.SHA1)
cnt, err := hr.CalcHashes()
Expect(err).To(BeNil())
Expect(cnt).To(Equal(int64(len(s))))
Expect(hr.GetBytes(0)).To(BeNil())
Expect(hr.GetString(crypto.SHA1)).To(Equal("5c075ed604db0adc524edd3516e8f0258ca6e58d"))

hr = iotools.NewHashReader(strings.NewReader(s), crypto.SHA1, crypto.MD5)
hr.Read(buf)
Expect(hr.GetBytes(crypto.SHA256)).To(BeNil())
Expand All @@ -70,5 +76,4 @@ var _ = Describe("Hash Reader Writer tests", func() {
Expect(hr.GetString(crypto.SHA1)).To(Equal("5c075ed604db0adc524edd3516e8f0258ca6e58d"))
Expect(hr.GetString(crypto.SHA1)).To(Equal("5c075ed604db0adc524edd3516e8f0258ca6e58d"))
})

})

0 comments on commit 72fa77a

Please sign in to comment.