github.com/google/syzkaller@v0.0.0-20251211124644-a066d2bc4b02/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 ...any) Sig { 17 h := sha1.New() 18 for _, data := range pieces { 19 if str, ok := data.(string); ok { 20 data = []byte(str) 21 } 22 if err := binary.Write(h, binary.LittleEndian, data); err != nil { 23 panic(err) 24 } 25 } 26 var sig Sig 27 copy(sig[:], h.Sum(nil)) 28 return sig 29 } 30 31 func String(pieces ...any) string { 32 sig := Hash(pieces...) 33 return sig.String() 34 } 35 36 func (sig *Sig) String() string { 37 return hex.EncodeToString((*sig)[:]) 38 } 39 40 // Truncate64 returns first 64 bits of the hash as int64. 41 func (sig *Sig) Truncate64() int64 { 42 var v int64 43 if err := binary.Read(bytes.NewReader((*sig)[:]), binary.LittleEndian, &v); err != nil { 44 panic(fmt.Sprintf("failed convert hash to id: %v", err)) 45 } 46 return v 47 }