aboutsummaryrefslogtreecommitdiff
path: root/hash.go
diff options
context:
space:
mode:
authorGravatar Runxi Yu2026-01-17 22:56:53 +0800
committerGravatar Runxi Yu2026-01-17 22:56:53 +0800
commit7a0ab5f77917a36a87945f6a88b036b9b6ba88ee (patch)
tree06947107af26e45bb5006276daa4b4d611f5dee2 /hash.go
parentREADME: Clarify that the sha1 build tag is for testing only (diff)
signatureNo signature
hash: Key by algorithm, not size
Diffstat (limited to 'hash.go')
-rw-r--r--hash.go61
1 files changed, 51 insertions, 10 deletions
diff --git a/hash.go b/hash.go
index 3edb6079..1a0053c2 100644
--- a/hash.go
+++ b/hash.go
@@ -8,44 +8,85 @@ import (
const maxHashSize = 32
+// hashAlgorithm identifies the hash algorithm used for Git object IDs.
+type hashAlgorithm uint8
+
+const (
+ hashAlgoUnknown hashAlgorithm = iota
+ hashAlgoSHA1
+ hashAlgoSHA256
+)
+
+// size returns the hash size in bytes.
+func (algo hashAlgorithm) size() int {
+ switch algo {
+ case hashAlgoSHA1:
+ return sha1.Size
+ case hashAlgoSHA256:
+ return sha256.Size
+ default:
+ return 0
+ }
+}
+
+// String returns the canonical name of the hash algorithm.
+func (algo hashAlgorithm) String() string {
+ switch algo {
+ case hashAlgoSHA1:
+ return "sha1"
+ case hashAlgoSHA256:
+ return "sha256"
+ default:
+ return "unknown"
+ }
+}
+
// Hash represents a Git object ID.
type Hash struct {
- size int
+ algo hashAlgorithm
data [maxHashSize]byte
}
// hashFunc is a function that computes a hash from input data.
type hashFunc func([]byte) Hash
-// hashFuncs maps hash size to hash function.
-var hashFuncs = map[int]hashFunc{
- sha1.Size: func(data []byte) Hash {
+// hashFuncs maps hash algorithm to hash function.
+var hashFuncs = map[hashAlgorithm]hashFunc{
+ hashAlgoSHA1: func(data []byte) Hash {
sum := sha1.Sum(data)
var h Hash
copy(h.data[:], sum[:])
- h.size = sha1.Size
+ h.algo = hashAlgoSHA1
return h
},
- sha256.Size: func(data []byte) Hash {
+ hashAlgoSHA256: func(data []byte) Hash {
sum := sha256.Sum256(data)
var h Hash
copy(h.data[:], sum[:])
- h.size = sha256.Size
+ h.algo = hashAlgoSHA256
return h
},
}
// String returns a hexadecimal string representation of the hash.
func (hash Hash) String() string {
- return hex.EncodeToString(hash.data[:hash.size])
+ size := hash.algo.size()
+ if size == 0 {
+ return ""
+ }
+ return hex.EncodeToString(hash.data[:size])
}
// Bytes returns a copy of the hash's bytes.
func (hash Hash) Bytes() []byte {
- return append([]byte(nil), hash.data[:hash.size]...)
+ size := hash.algo.size()
+ if size == 0 {
+ return nil
+ }
+ return append([]byte(nil), hash.data[:size]...)
}
// Size returns the hash size.
func (hash Hash) Size() int {
- return hash.size
+ return hash.algo.size()
}