From e79da50422b13d425d5046b8515fd00b5f3848f8 Mon Sep 17 00:00:00 2001 From: Or Waichman Date: Mon, 4 Mar 2024 11:23:59 +0200 Subject: [PATCH] Checksum returns bytes too --- utils/checksum.go | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/utils/checksum.go b/utils/checksum.go index 7503c34f..ee3ac0ee 100644 --- a/utils/checksum.go +++ b/utils/checksum.go @@ -51,6 +51,25 @@ func GetFileChecksums(filePath string) (md5, sha1, sha2 string, err error) { // 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() @@ -64,8 +83,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 { @@ -76,6 +94,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 {