Debian Codegraph @

plumbing/hash/hash.go

raw
1 // package hash provides a way for managing the
2 // underlying hash implementations used across go-git.
3 package hash
4
5 import (
6 "crypto"
7 "fmt"
8 "hash"
9
10 "github.com/pjbgf/sha1cd"
11 )
12
13 // algos is a map of hash algorithms.
14 var algos = map[crypto.Hash]func() hash.Hash{}
15
16 func init() {
17 reset()
18 }
19
20 // reset resets the default algos value. Can be used after running tests
21 // that registers new algorithms to avoid side effects.
22 func reset() {
23 algos[crypto.SHA1] = sha1cd.New
24 algos[crypto.SHA256] = crypto.SHA256.New
25 }
26
27 // RegisterHash allows for the hash algorithm used to be overridden.
28 // This ensures the hash selection for go-git must be explicit, when
29 // overriding the default value.
30 func RegisterHash(h crypto.Hash, f func() hash.Hash) error {
31 if f == nil {
32 return fmt.Errorf("cannot register hash: f is nil")
33 }
34
35 switch h {
36 case crypto.SHA1:
37 algos[h] = f
38 case crypto.SHA256:
39 algos[h] = f
40 default:
41 return fmt.Errorf("unsupported hash function: %v", h)
42 }
43 return nil
44 }
45
46 // Hash is the same as hash.Hash. This allows consumers
47 // to not having to import this package alongside "hash".
48 type Hash interface {
49 hash.Hash
50 }
51
52 // New returns a new Hash for the given hash function.
53 // It panics if the hash function is not registered.
54 func New(h crypto.Hash) Hash {
55 hh, ok := algos[h]
56 if !ok {
57 panic(fmt.Sprintf("hash algorithm not registered: %v", h))
58 }
59 return hh()
60 }