diff --git a/errors.go b/errors.go new file mode 100644 index 0000000..7a8a56a --- /dev/null +++ b/errors.go @@ -0,0 +1,14 @@ +package gohashtree + +import "errors" + +var ( + // ErrOddChunks is returned when the number of chunks is odd. + ErrOddChunks = errors.New("odd number of chunks") + // ErrNotEnoughDigests is returned when the number of digests is not enough. + ErrNotEnoughDigests = errors.New("not enough digest length") + // ErrChunksNotMultipleOf64 is returned when the chunks are not multiple of 64 bytes. + ErrChunksNotMultipleOf64 = errors.New("chunks not multiple of 64 bytes") + // ErrDigestsNotMultipleOf32 is returned when the digests are not multiple of 32 bytes. + ErrDigestsNotMultipleOf32 = errors.New("digests not multiple of 32 bytes") +) diff --git a/hash.go b/hash.go index b9675e4..e009335 100644 --- a/hash.go +++ b/hash.go @@ -38,10 +38,10 @@ func Hash(digests [][32]byte, chunks [][32]byte) error { } if len(chunks)%2 == 1 { - return fmt.Errorf("odd number of chunks") + return ErrOddChunks } if len(digests) < len(chunks)/2 { - return fmt.Errorf("not enough digest length, need at least %v, got %v", len(chunks)/2, len(digests)) + return fmt.Errorf("%w: need at least %v, got %v", ErrNotEnoughDigests, len(chunks)/2, len(digests)) } if supportedCPU { _hash(&digests[0][0], chunks, uint32(len(chunks)/2)) @@ -64,14 +64,17 @@ func HashByteSlice(digests []byte, chunks []byte) error { if len(chunks) == 0 { return nil } + if len(chunks)%64 != 0 { - return fmt.Errorf("chunks not multiple of 64 bytes") + return ErrChunksNotMultipleOf64 } + if len(digests)%32 != 0 { - return fmt.Errorf("digests not multiple of 32 bytes") + return ErrDigestsNotMultipleOf32 } + if len(digests) < len(chunks)/2 { - return fmt.Errorf("not enough digest length, need at least %d, got %d", len(chunks)/2, len(digests)) + return fmt.Errorf("%w: need at least %v, got %v", ErrNotEnoughDigests, len(chunks)/2, len(digests)) } // We use an unsafe pointer to cast []byte to [][32]byte. The length and // capacity of the slice need to be divided accordingly by 32. diff --git a/hash_test.go b/hash_test.go index 53dbb69..6f4beac 100644 --- a/hash_test.go +++ b/hash_test.go @@ -24,6 +24,7 @@ SOFTWARE. package gohashtree_test import ( + "errors" "reflect" "testing" @@ -283,7 +284,7 @@ func TestNotAllocatedDigest(t *testing.T) { chunks := make([][32]byte, 4) err := gohashtree.Hash(digests, chunks) expected := "not enough digest length, need at least 2, got 1" - if err.Error() != expected { + if !errors.Is(err, gohashtree.ErrNotEnoughDigests) { t.Logf("expected error: \"%s\", got: \"%s\"", expected, err) t.Fail() }