-
Notifications
You must be signed in to change notification settings - Fork 1
/
object_hasher.go
82 lines (66 loc) · 1.61 KB
/
object_hasher.go
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
71
72
73
74
75
76
77
78
79
80
81
82
package pipelines
import (
"crypto/sha1"
"hash"
"sort"
)
var hashFieldSeparator = []byte{0}
type ObjectHasher struct {
h hash.Hash
}
func NewObjectHasher() ObjectHasher {
return ObjectHasher{
sha1.New(),
}
}
func (oh ObjectHasher) WriteStringField(value string) {
oh.h.Write([]byte(value))
oh.WriteFieldSeparator()
}
func (oh ObjectHasher) WriteMapField(value map[string]string) {
keys := make([]string, 0, len(value))
for k := range value {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
oh.WriteStringField(k)
oh.WriteStringField(value[k])
}
oh.WriteFieldSeparator()
}
type KV interface {
GetKey() string
GetValue() string
}
// Has to be a function with parameter because Go does not support generic methods
func WriteKVListField[T KV](oh ObjectHasher, kvs []T) {
WriteList(oh, kvs, func(kv1, kv2 T) bool {
if kv1.GetKey() != kv2.GetKey() {
return kv1.GetKey() < kv2.GetKey()
} else {
return kv1.GetValue() < kv2.GetValue()
}
}, func(oh ObjectHasher, kv T) {
oh.WriteStringField(kv.GetKey())
oh.WriteStringField(kv.GetValue())
})
}
// Has to be a function with parameter because Go does not support generic methods
func WriteList[T any](oh ObjectHasher, ts []T, cmp func(t1, t2 T) bool, write func(oh ObjectHasher, t T)) {
sorted := make([]T, len(ts))
copy(sorted, ts)
sort.Slice(sorted, func(i, j int) bool {
return cmp(sorted[i], sorted[j])
})
for _, k := range sorted {
write(oh, k)
}
oh.WriteFieldSeparator()
}
func (oh ObjectHasher) WriteFieldSeparator() {
oh.h.Write(hashFieldSeparator)
}
func (oh ObjectHasher) Sum() []byte {
return oh.h.Sum(nil)
}