From 95bee1895a85e8eadd41a8fb69212b56fadcbf5b Mon Sep 17 00:00:00 2001 From: Stephen J Day Date: Tue, 29 Dec 2015 15:24:32 -0800 Subject: [PATCH] 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 --- digest/digester.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/digest/digester.go b/digest/digester.go index cbb2e368..bce4514f 100644 --- a/digest/digester.go +++ b/digest/digester.go @@ -2,6 +2,7 @@ package digest import ( "crypto" + "fmt" "hash" "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 -// returned. Make sure to check Available before calling. +// Hash returns a new hash as used by the algorithm. If not available, the +// method will panic. Check Algorithm.Available() before calling. func (a Algorithm) Hash() hash.Hash { 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()