common: unify hex prefix check code (#19937)

This commit is contained in:
lmittmann 2019-08-22 11:45:07 +02:00 committed by Felix Lange
parent 7c229941ac
commit 1cd5bf080e
2 changed files with 5 additions and 7 deletions

@ -43,10 +43,8 @@ func ToHexArray(b [][]byte) []string {
// FromHex returns the bytes represented by the hexadecimal string s. // FromHex returns the bytes represented by the hexadecimal string s.
// s may be prefixed with "0x". // s may be prefixed with "0x".
func FromHex(s string) []byte { func FromHex(s string) []byte {
if len(s) > 1 { if has0xPrefix(s) {
if s[0:2] == "0x" || s[0:2] == "0X" { s = s[2:]
s = s[2:]
}
} }
if len(s)%2 == 1 { if len(s)%2 == 1 {
s = "0" + s s = "0" + s
@ -65,8 +63,8 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
return return
} }
// hasHexPrefix validates str begins with '0x' or '0X'. // has0xPrefix validates str begins with '0x' or '0X'.
func hasHexPrefix(str string) bool { func has0xPrefix(str string) bool {
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
} }

@ -193,7 +193,7 @@ func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }
// IsHexAddress verifies whether a string can represent a valid hex-encoded // IsHexAddress verifies whether a string can represent a valid hex-encoded
// Ethereum address or not. // Ethereum address or not.
func IsHexAddress(s string) bool { func IsHexAddress(s string) bool {
if hasHexPrefix(s) { if has0xPrefix(s) {
s = s[2:] s = s[2:]
} }
return len(s) == 2*AddressLength && isHex(s) return len(s) == 2*AddressLength && isHex(s)