forked from TrueCloudLab/distribution
digest: panic on unavailable hash algorithm
After running into a few nil pointer errors during development, it is clear that having this function return nil when a hash is not available is the wrong approach. Nearly every time, this lack of availability was due to a missing import statement for the hash. This is always a programming error. To avoid future confusion, we now appropriately panic when the hash function is not imported by the application. More dynamic uses of the package should call Algorithm.Available() before calling Algorithm.Hash() to avoid this panic. Signed-off-by: Stephen J Day <stephen.day@docker.com>
This commit is contained in:
parent
e02a0b0399
commit
95bee1895a
1 changed files with 11 additions and 3 deletions
|
@ -2,6 +2,7 @@ package digest
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto"
|
"crypto"
|
||||||
|
"fmt"
|
||||||
"hash"
|
"hash"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
@ -84,11 +85,18 @@ func (a Algorithm) New() Digester {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hash returns a new hash as used by the algorithm. If not available, nil is
|
// Hash returns a new hash as used by the algorithm. If not available, the
|
||||||
// returned. Make sure to check Available before calling.
|
// method will panic. Check Algorithm.Available() before calling.
|
||||||
func (a Algorithm) Hash() hash.Hash {
|
func (a Algorithm) Hash() hash.Hash {
|
||||||
if !a.Available() {
|
if !a.Available() {
|
||||||
return nil
|
// NOTE(stevvooe): A missing hash is usually a programming error that
|
||||||
|
// must be resolved at compile time. We don't import in the digest
|
||||||
|
// package to allow users to choose their hash implementation (such as
|
||||||
|
// when using stevvooe/resumable or a hardware accelerated package).
|
||||||
|
//
|
||||||
|
// Applications that may want to resolve the hash at runtime should
|
||||||
|
// call Algorithm.Available before call Algorithm.Hash().
|
||||||
|
panic(fmt.Sprintf("%v not available (make sure it is imported)", a))
|
||||||
}
|
}
|
||||||
|
|
||||||
return algorithms[a].New()
|
return algorithms[a].New()
|
||||||
|
|
Loading…
Reference in a new issue