blob: 26a3b04f16f880bd021cf51363533c91022d9d79 (
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
|
// Copyright 2016 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package hash
import (
"bytes"
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
)
type Sig [sha1.Size]byte
func Hash(pieces ...any) Sig {
h := sha1.New()
for _, data := range pieces {
if str, ok := data.(string); ok {
data = []byte(str)
}
retry:
if binary.Write(h, binary.LittleEndian, data) == nil {
continue
}
marshalled, err := json.Marshal(data)
if err != nil {
panic(err)
}
data = marshalled
goto retry
}
var sig Sig
copy(sig[:], h.Sum(nil))
return sig
}
func String(pieces ...any) string {
sig := Hash(pieces...)
return sig.String()
}
func (sig *Sig) String() string {
return hex.EncodeToString((*sig)[:])
}
// Truncate64 returns first 64 bits of the hash as int64.
func (sig *Sig) Truncate64() int64 {
var v int64
if err := binary.Read(bytes.NewReader((*sig)[:]), binary.LittleEndian, &v); err != nil {
panic(fmt.Sprintf("failed convert hash to id: %v", err))
}
return v
}
|