shithub: furgit

Download patch

ref: 7644a12dd8fbeb0c936848a4bc5cef423a8fc2b7
parent: fd89c1614193d5d86b1606e1819172fca3473311
author: Runxi Yu <me@runxiyu.org>
date: Thu Jan 29 16:17:25 EST 2026

hash: Make streaming hashes possible

--- a/hash.go
+++ b/hash.go
@@ -4,6 +4,7 @@
 	"crypto/sha1"
 	"crypto/sha256"
 	"encoding/hex"
+	"hash"
 )
 
 // maxHashSize MUST be >= the largest supported algorithm size.
@@ -22,6 +23,7 @@
 	name string
 	size int
 	sum  func([]byte) Hash
+	new  func() hash.Hash
 }
 
 var hashAlgorithmTable = [...]hashAlgorithmDetails{
@@ -36,6 +38,9 @@
 			h.algo = hashAlgoSHA1
 			return h
 		},
+		new: func() hash.Hash {
+			return sha1.New()
+		},
 	},
 	hashAlgoSHA256: {
 		name: "sha256",
@@ -47,6 +52,9 @@
 			h.algo = hashAlgoSHA256
 			return h
 		},
+		new: func() hash.Hash {
+			return sha256.New()
+		},
 	},
 }
 
@@ -74,6 +82,14 @@
 
 func (algo hashAlgorithm) Sum(data []byte) Hash {
 	return algo.info().sum(data)
+}
+
+func (algo hashAlgorithm) New() (hash.Hash, error) {
+	newFn := algo.info().new
+	if newFn == nil {
+		return nil, ErrInvalidObject
+	}
+	return newFn(), nil
 }
 
 // Hash represents a Git object ID.
--- a/packed_write_pack.go
+++ b/packed_write_pack.go
@@ -2,8 +2,6 @@
 
 import (
 	"crypto/rand"
-	"crypto/sha1"
-	"crypto/sha256"
 	"encoding/binary"
 	"errors"
 	"hash"
@@ -29,7 +27,7 @@
 	if w == nil {
 		return nil, ErrInvalidObject
 	}
-	h, err := newHashWriter(algo)
+	h, err := algo.New()
 	if err != nil {
 		return nil, err
 	}
@@ -39,17 +37,6 @@
 		algo:     algo,
 		objCount: objCount,
 	}, nil
-}
-
-func newHashWriter(algo hashAlgorithm) (hash.Hash, error) {
-	switch algo {
-	case hashAlgoSHA1:
-		return sha1.New(), nil
-	case hashAlgoSHA256:
-		return sha256.New(), nil
-	default:
-		return nil, ErrInvalidObject
-	}
 }
 
 func (pw *packWriter) writePacked(p []byte) error {
--