aboutsummaryrefslogtreecommitdiffstats
path: root/internal/hash.go
blob: 0540db1825b5edc1bbf1aaf8fb0f78271676db76 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package internal

import (
	"crypto/sha1"
	"encoding/hex"
	"strconv"
)

// Hash SHA1 hased content
type Hash [20]byte

// 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))
}

// NewHash return a new Hash from a hexadecimal hash representation
func NewHash(s string) Hash {
	b, _ := hex.DecodeString(s)

	var h Hash
	copy(h[:], b)

	return h
}

func (h Hash) IsZero() bool {
	var empty Hash
	return h == empty
}

func (h Hash) String() string {
	return hex.EncodeToString(h[:])
}