From 240b07788c0ca24d142f8df7fcb6fc7444bc875a Mon Sep 17 00:00:00 2001 From: Dmitry Vyukov Date: Fri, 21 Jul 2017 09:04:03 +0200 Subject: pkg/hash: allow to hash multiple byte slices Hash/String now allow to hash mutiple byte slices without copying them into a single slice first. --- pkg/hash/hash.go | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) (limited to 'pkg') diff --git a/pkg/hash/hash.go b/pkg/hash/hash.go index 4c45ba6e6..ea67db3e2 100644 --- a/pkg/hash/hash.go +++ b/pkg/hash/hash.go @@ -4,19 +4,27 @@ package hash import ( + "bytes" "crypto/sha1" + "encoding/binary" "encoding/hex" "fmt" ) type Sig [sha1.Size]byte -func Hash(data []byte) Sig { - return Sig(sha1.Sum(data)) +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(data []byte) string { - sig := Hash(data) +func String(pieces ...[]byte) string { + sig := Hash(pieces...) return sig.String() } @@ -24,6 +32,15 @@ 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 { -- cgit mrf-deployment