Skip to content

Commit

Permalink
consilidated isValidHex usage
Browse files Browse the repository at this point in the history
  • Loading branch information
abi87 committed Oct 1, 2024
1 parent 320256c commit 8f9f7a4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 21 deletions.
28 changes: 14 additions & 14 deletions mod/primitives/pkg/encoding/hex/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

package hex

import "errors"

// has0xPrefix returns true if s has a 0x prefix.
func has0xPrefix[T []byte | string](s T) bool {
return len(s) >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')
Expand Down Expand Up @@ -56,28 +58,26 @@ func isQuotedString[T []byte | string](input T) bool {

// formatAndValidateText validates the input text for a hex string.
func formatAndValidateText(input []byte) ([]byte, error) {
if len(input) == 0 {
switch err := isValidHex(input); {
case err == nil:
input = input[2:]
if len(input)%2 != 0 {
return nil, ErrOddLength
}
return input, nil
case errors.Is(err, ErrMissingPrefix):
return nil, nil // empty strings are allowed
default:
return nil, err
}
if !has0xPrefix(input) {
return nil, ErrMissingPrefix
}
input = input[2:]
if len(input)%2 != 0 {
return nil, ErrOddLength
}
return input, nil
}

// formatAndValidateNumber checks the input text for a hex number.
func formatAndValidateNumber[T []byte | string](input T) (T, error) {
// realistically, this shouldn't rarely error if called on
// unwrapped hex.String
if len(input) == 0 {
return *new(T), ErrEmptyString
}
if !has0xPrefix(input) {
return *new(T), ErrMissingPrefix
if err := isValidHex(input); err != nil {
return *new(T), err
}
input = input[2:]
if len(input) == 0 {
Expand Down
11 changes: 4 additions & 7 deletions mod/primitives/pkg/encoding/hex/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (s *String) UnmarshalText(text []byte) error {
return nil
}

func isValidHex(str string) error {
func isValidHex[T []byte | string](str T) error {
if len(str) == 0 {
return ErrEmptyString
} else if !has0xPrefix(str) {
Expand All @@ -67,13 +67,10 @@ func isValidHex(str string) error {
// NewStringStrict creates a hex string with 0x prefix. It errors if any of the
// string invariants are violated.
func NewStringStrict[T []byte | string](s T) (String, error) {
str := string(s)
if len(str) == 0 {
return "", ErrEmptyString
} else if !has0xPrefix(str) {
return "", ErrMissingPrefix
if err := isValidHex(s); err != nil {
return "", err
}
return String(str), nil
return String(s), nil
}

// FromBytes creates a hex string with 0x prefix.
Expand Down

0 comments on commit 8f9f7a4

Please sign in to comment.