Skip to content

Commit

Permalink
Checksum returns bytes too (#238)
Browse files Browse the repository at this point in the history
  • Loading branch information
orwaichman authored Mar 7, 2024
1 parent f06014f commit ce2b8a6
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions utils/checksum.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ func GetFileChecksums(filePath string, checksumType ...Algorithm) (checksums map

// CalcChecksums calculates all hashes at once using AsyncMultiWriter. The file is therefore read only once.
func CalcChecksums(reader io.Reader, checksumType ...Algorithm) (map[Algorithm]string, error) {
hashes, err := calcChecksums(reader, checksumType...)
if err != nil {
return nil, err
}
results := sumResults(hashes)
return results, nil
}

// CalcChecksumsBytes calculates hashes like `CalcChecksums`, returns result as bytes
func CalcChecksumsBytes(reader io.Reader, checksumType ...Algorithm) (map[Algorithm][]byte, error) {
hashes, err := calcChecksums(reader, checksumType...)
if err != nil {
return nil, err
}
results := sumResultsBytes(hashes)
return results, nil
}

func calcChecksums(reader io.Reader, checksumType ...Algorithm) (map[Algorithm]hash.Hash, error) {
hashes := getChecksumByAlgorithm(checksumType...)
var multiWriter io.Writer
pageSize := os.Getpagesize()
Expand All @@ -58,8 +77,7 @@ func CalcChecksums(reader io.Reader, checksumType ...Algorithm) (map[Algorithm]s
if err != nil {
return nil, err
}
results := sumResults(hashes)
return results, nil
return hashes, nil
}

func sumResults(hashes map[Algorithm]hash.Hash) map[Algorithm]string {
Expand All @@ -70,6 +88,14 @@ func sumResults(hashes map[Algorithm]hash.Hash) map[Algorithm]string {
return results
}

func sumResultsBytes(hashes map[Algorithm]hash.Hash) map[Algorithm][]byte {
results := map[Algorithm][]byte{}
for k, v := range hashes {
results[k] = v.Sum(nil)
}
return results
}

func getChecksumByAlgorithm(checksumType ...Algorithm) map[Algorithm]hash.Hash {
hashes := map[Algorithm]hash.Hash{}
if len(checksumType) == 0 {
Expand Down

0 comments on commit ce2b8a6

Please sign in to comment.