debian-mirror-gitlab/workhorse/internal/upload/destination/multi_hash.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

71 lines
1.2 KiB
Go
Raw Normal View History

2022-05-07 20:08:51 +05:30
package destination
2021-02-22 17:27:13 +05:30
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"hash"
"io"
)
var hashFactories = map[string](func() hash.Hash){
"md5": md5.New,
"sha1": sha1.New,
"sha256": sha256.New,
"sha512": sha512.New,
}
2022-08-13 15:12:31 +05:30
func factories() map[string](func() hash.Hash) {
return hashFactories
}
2023-03-17 16:20:25 +05:30
type multiHash struct {
io.Writer
hashes map[string]hash.Hash
}
func permittedHashFunction(hashFunctions []string, hash string) bool {
if len(hashFunctions) == 0 {
2022-08-13 15:12:31 +05:30
return true
}
2023-03-17 16:20:25 +05:30
for _, name := range hashFunctions {
if name == hash {
return true
}
}
2022-08-13 15:12:31 +05:30
2023-03-17 16:20:25 +05:30
return false
2021-02-22 17:27:13 +05:30
}
2023-03-17 16:20:25 +05:30
func newMultiHash(hashFunctions []string) (m *multiHash) {
2021-02-22 17:27:13 +05:30
m = &multiHash{}
m.hashes = make(map[string]hash.Hash)
var writers []io.Writer
2022-08-13 15:12:31 +05:30
for hash, hashFactory := range factories() {
2023-03-17 16:20:25 +05:30
if !permittedHashFunction(hashFunctions, hash) {
continue
}
2021-02-22 17:27:13 +05:30
writer := hashFactory()
m.hashes[hash] = writer
writers = append(writers, writer)
}
m.Writer = io.MultiWriter(writers...)
return m
}
func (m *multiHash) finish() map[string]string {
h := make(map[string]string)
for hashName, hash := range m.hashes {
checksum := hash.Sum(nil)
h[hashName] = hex.EncodeToString(checksum)
}
return h
}