-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
hash.go
55 lines (47 loc) · 1.17 KB
/
hash.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
// 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"
"fmt"
)
type Sig [sha1.Size]byte
func Hash(pieces ...[]byte) Sig {
h := sha1.New()
for _, data := range pieces {
h.Write(data)
}
var sig Sig
copy(sig[:], h.Sum(nil))
return sig
}
func String(pieces ...[]byte) 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
}
func FromString(str string) (Sig, error) {
bin, err := hex.DecodeString(str)
if err != nil {
return Sig{}, fmt.Errorf("failed to decode sig '%v': %w", str, err)
}
if len(bin) != len(Sig{}) {
return Sig{}, fmt.Errorf("failed to decode sig '%v': bad len", str)
}
var sig Sig
copy(sig[:], bin[:])
return sig, err
}