github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/hash/hash.go (about) 1 // Copyright 2016 syzkaller project authors. All rights reserved. 2 // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. 3 4 package hash 5 6 import ( 7 "bytes" 8 "crypto/sha1" 9 "encoding/binary" 10 "encoding/hex" 11 "fmt" 12 ) 13 14 type Sig [sha1.Size]byte 15 16 func Hash(pieces ...[]byte) Sig { 17 h := sha1.New() 18 for _, data := range pieces { 19 h.Write(data) 20 } 21 var sig Sig 22 copy(sig[:], h.Sum(nil)) 23 return sig 24 } 25 26 func String(pieces ...[]byte) string { 27 sig := Hash(pieces...) 28 return sig.String() 29 } 30 31 func (sig *Sig) String() string { 32 return hex.EncodeToString((*sig)[:]) 33 } 34 35 // Truncate64 returns first 64 bits of the hash as int64. 36 func (sig *Sig) Truncate64() int64 { 37 var v int64 38 if err := binary.Read(bytes.NewReader((*sig)[:]), binary.LittleEndian, &v); err != nil { 39 panic(fmt.Sprintf("failed convert hash to id: %v", err)) 40 } 41 return v 42 } 43 44 func FromString(str string) (Sig, error) { 45 bin, err := hex.DecodeString(str) 46 if err != nil { 47 return Sig{}, fmt.Errorf("failed to decode sig '%v': %w", str, err) 48 } 49 if len(bin) != len(Sig{}) { 50 return Sig{}, fmt.Errorf("failed to decode sig '%v': bad len", str) 51 } 52 var sig Sig 53 copy(sig[:], bin[:]) 54 return sig, err 55 }