diff options
| author | Dmitry Vyukov <dvyukov@google.com> | 2017-07-21 09:04:03 +0200 |
|---|---|---|
| committer | Dmitry Vyukov <dvyukov@google.com> | 2017-07-21 10:06:46 +0200 |
| commit | 240b07788c0ca24d142f8df7fcb6fc7444bc875a (patch) | |
| tree | 28411e20ba46259cdb45805d5a9fc9d2d53cd403 /pkg/hash | |
| parent | c5d0c9e31884dac4df9e8095e579c87076c580d4 (diff) | |
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.
Diffstat (limited to 'pkg/hash')
| -rw-r--r-- | pkg/hash/hash.go | 25 |
1 files changed, 21 insertions, 4 deletions
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 { |
