Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions core/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package core
import (
"crypto/sha1"
"encoding/hex"
"hash"
"strconv"
)

Expand All @@ -14,13 +15,9 @@ var ZeroHash Hash

// ComputeHash compute the hash for a given ObjectType and content
func ComputeHash(t ObjectType, content []byte) Hash {
h := t.Bytes()
h = append(h, ' ')
h = strconv.AppendInt(h, int64(len(content)), 10)
h = append(h, 0)
h = append(h, content...)

return Hash(sha1.Sum(h))
h := NewHasher(t, int64(len(content)))
h.Write(content)
return h.Sum()
}

// NewHash return a new Hash from a hexadecimal hash representation
Expand All @@ -41,3 +38,21 @@ func (h Hash) IsZero() bool {
func (h Hash) String() string {
return hex.EncodeToString(h[:])
}

type Hasher struct {
hash.Hash
}

func NewHasher(t ObjectType, size int64) Hasher {
h := Hasher{sha1.New()}
h.Write(t.Bytes())
h.Write([]byte(" "))
h.Write([]byte(strconv.FormatInt(size, 10)))
h.Write([]byte{0})
return h
}

func (h Hasher) Sum() (hash Hash) {
copy(hash[:], h.Hash.Sum(nil))
return
}
7 changes: 7 additions & 0 deletions core/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,10 @@ func (s *HashSuite) TestIsZero(c *C) {
hash = NewHash("8ab686eafeb1f44702738c8b0f24f2567c36da6d")
c.Assert(hash.IsZero(), Equals, false)
}

func (s *HashSuite) TestNewHasher(c *C) {
content := "hasher test sample"
hasher := NewHasher(BlobObject, int64(len(content)))
hasher.Write([]byte(content))
c.Assert(hasher.Sum().String(), Equals, "dc42c3cc80028d0ec61f0a6b24cadd1c195c4dfc")
}