summaryrefslogtreecommitdiff
path: root/workhorse/internal/upload/destination/multi_hash.go
blob: 3f8b0cbd9036d28cefc8dc631594455653f917c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package destination

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,
}

func factories() map[string](func() hash.Hash) {
	return hashFactories
}

type multiHash struct {
	io.Writer
	hashes map[string]hash.Hash
}

func permittedHashFunction(hashFunctions []string, hash string) bool {
	if len(hashFunctions) == 0 {
		return true
	}

	for _, name := range hashFunctions {
		if name == hash {
			return true
		}
	}

	return false
}

func newMultiHash(hashFunctions []string) (m *multiHash) {
	m = &multiHash{}
	m.hashes = make(map[string]hash.Hash)

	var writers []io.Writer
	for hash, hashFactory := range factories() {
		if !permittedHashFunction(hashFunctions, hash) {
			continue
		}

		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
}