@@ -9,7 +9,36 @@ import (
99 "strings"
1010)
1111
12- var hashes = make ([]func () hash.Hash , maxHash )
12+ var (
13+ hashes = make ([]func () hash.Hash , maxHash )
14+ hashesByName = make (map [string ]func () hash.Hash )
15+ )
16+
17+ func findStdHashByName (name string ) Hash {
18+ for h := range maxHash {
19+ if h .String () == name {
20+ return h
21+ }
22+ }
23+ return maxHash
24+ }
25+
26+ // NewHash returns a new hash.Hash object for the given hash function name.
27+ // It can be a standard hash function (e.g. "MIMC_BN254"),
28+ // or a custom hash function defined by the user through [RegisterCustomHash].
29+ func NewHash (name string ) hash.Hash {
30+ // first see if it's a standard hash function
31+ if h := findStdHashByName (name ); h < maxHash {
32+ return h .New ()
33+ }
34+
35+ // see if it's a custom hash function - registered by the user
36+ if f , ok := hashesByName [name ]; ok {
37+ return f ()
38+ }
39+
40+ panic (fmt .Errorf ("hash function \" %s\" not registered" , name ))
41+ }
1342
1443// RegisterHash registers a new hash function constructor. Should be called in
1544// the init function of the hash package.
@@ -20,7 +49,16 @@ func RegisterHash(h Hash, new func() hash.Hash) {
2049 hashes [h ] = new
2150}
2251
23- // Hash defines an unique identifier for a hash function.
52+ // RegisterCustomHash registers a new hash function constructor, retrievable by name
53+ // using NewHash. It does not allow overwriting standard hash functions.
54+ func RegisterCustomHash (name string , new func () hash.Hash ) {
55+ if h := findStdHashByName (name ); h < maxHash {
56+ panic (fmt .Errorf ("cannot overwrite standard hash function \" %s\" " , name ))
57+ }
58+ hashesByName [name ] = new
59+ }
60+
61+ // Hash defines a unique identifier for a hash function.
2462type Hash uint
2563
2664const (
0 commit comments