-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
pkg/hash: add FromHashTypeAndDigest function
This allows creating a Hash from a hashType and digest. We don't populate unused h.hash anymore, as ParseNixBase32 now uses FromHashTypeAndDigest too, and the size checks are done there.
- Loading branch information
Showing
3 changed files
with
37 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package hash | ||
|
||
import ( | ||
"fmt" | ||
|
||
mh "github.com/multiformats/go-multihash/core" | ||
) | ||
|
||
// FromHashTypeAndDigest constructs a Hash from hashType and digest. | ||
// hashType needs to be a supported multihash type, | ||
// and the digest len needs to be correct, otherwise an error is returned. | ||
func FromHashTypeAndDigest(hashType int, digest []byte) (*Hash, error) { | ||
var expectedDigestSize int | ||
|
||
switch hashType { | ||
case mh.SHA1: | ||
expectedDigestSize = 20 | ||
case mh.SHA2_256: | ||
expectedDigestSize = 32 | ||
case mh.SHA2_512: | ||
expectedDigestSize = 64 | ||
default: | ||
return nil, fmt.Errorf("unknown hash type: %d", hashType) | ||
} | ||
|
||
if len(digest) != expectedDigestSize { | ||
return nil, fmt.Errorf("wrong digest len, expected %d, got %d", expectedDigestSize, len(digest)) | ||
} | ||
|
||
return &Hash{ | ||
HashType: hashType, | ||
hash: nil, | ||
bytesWritten: 0, | ||
digest: digest, | ||
}, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters