aboutsummaryrefslogtreecommitdiff
path: root/hash.go
diff options
context:
space:
mode:
authorGravatar Runxi Yu2025-11-16 00:00:00 +0000
committerGravatar Runxi Yu2025-11-16 00:00:00 +0000
commit9ac827977b8f430906110ecd2030324248fff604 (patch)
treeb0f8fdb46252bef429beb27190a2cfc0cbd42540 /hash.go
parentREADME: Add my Villosa instance (diff)
signature
Support multiple hash sizes in one build
Diffstat (limited to 'hash.go')
-rw-r--r--hash.go43
1 files changed, 33 insertions, 10 deletions
diff --git a/hash.go b/hash.go
index 3c6ff6ac..336d5322 100644
--- a/hash.go
+++ b/hash.go
@@ -1,17 +1,40 @@
package furgit
import (
+ "crypto/sha1"
+ "crypto/sha256"
"encoding/hex"
"fmt"
)
+const maxHashSize = 32
+
// Hash represents a Git object identifier.
-type Hash [HashSize]byte
+type Hash [maxHashSize]byte
+
+// hashFunc is a function that computes a hash from input data.
+type hashFunc func([]byte) [maxHashSize]byte
+
+// hashFuncs maps hash size to hash function.
+var hashFuncs = map[int]hashFunc{
+ sha1.Size: func(data []byte) [maxHashSize]byte {
+ var result [maxHashSize]byte
+ sum := sha1.Sum(data)
+ copy(result[:], sum[:])
+ return result
+ },
+ sha256.Size: func(data []byte) [maxHashSize]byte {
+ var result [maxHashSize]byte
+ sum := sha256.Sum256(data)
+ copy(result[:], sum[:])
+ return result
+ },
+}
-// ParseHash converts a hex string into an Hash.
-func ParseHash(s string) (Hash, error) {
+// ParseHashWithSize converts a hex string into a Hash for a given hash size.
+func ParseHashWithSize(s string, hashSize int) (Hash, error) {
var id Hash
- if len(s) != HashSize*2 {
+ if len(s) != hashSize*2 {
return id, fmt.Errorf("furgit: invalid hash length %d", len(s))
}
data, err := hex.DecodeString(s)
@@ -22,12 +45,12 @@ func ParseHash(s string) (Hash, error) {
return id, nil
}
-// String renders the ID as hex.
-func (id Hash) String() string {
- return hex.EncodeToString(id[:])
+// StringWithSize returns the ID as hex for a given hash size.
+func (id Hash) StringWithSize(hashSize int) string {
+ return hex.EncodeToString(id[:hashSize])
}
-// Bytes returns a mutable copy of the underlying bytes.
-func (id Hash) Bytes() []byte {
- return append([]byte(nil), id[:]...)
+// BytesWithSize returns a mutable copy of the underlying bytes for a given hash size.
+func (id Hash) BytesWithSize(hashSize int) []byte {
+ return append([]byte(nil), id[:hashSize]...)
}