Skip to content

Commit

Permalink
improve: adding handling of odd-length hex strings in .
Browse files Browse the repository at this point in the history
Signed-off-by: Nikolay Nedkov <[email protected]>
  • Loading branch information
Psykepro committed Aug 31, 2023
1 parent f87b334 commit 419e7ca
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
6 changes: 6 additions & 0 deletions hex/hex.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ func DecodeString(str string) ([]byte, error) {
func DecodeHex(str string) ([]byte, error) {
str = strings.TrimPrefix(str, "0x")

// Check if the string has an odd length
if len(str)%2 != 0 {
// Prepend a '0' to make it even-length
str = "0" + str
}

return hex.DecodeString(str)
}

Expand Down
36 changes: 36 additions & 0 deletions hex/hex_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package hex

import (
"encoding/hex"
"math"
"math/big"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestEncodeDecodeBig(t *testing.T) {
Expand All @@ -14,3 +16,37 @@ func TestEncodeDecodeBig(t *testing.T) {
d := DecodeBig(e)
assert.Equal(t, b.Uint64(), d.Uint64())
}

// Define a struct for test cases
type TestCase struct {
input string
output []byte
err error
}

// Unit test function
func TestDecodeHex(t *testing.T) {
testCases := []TestCase{
{"0", []byte{0}, nil},
{"00", []byte{0}, nil},
{"0x0", []byte{0}, nil},
{"0x00", []byte{0}, nil},
{"1", []byte{1}, nil},
{"01", []byte{1}, nil},
{"", []byte{}, hex.ErrLength},
{"0x", []byte{}, hex.ErrLength},
{"zz", []byte{}, hex.InvalidByteError('z')},
}

for _, tc := range testCases {
t.Run(tc.input, func(t *testing.T) {
output, err := DecodeHex(tc.input)
if tc.err != nil {
require.Error(t, tc.err, err)
} else {
require.NoError(t, err)
}
require.Equal(t, output, tc.output)
})
}
}

0 comments on commit 419e7ca

Please sign in to comment.