mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-23 05:06:43 +00:00
refactor: replace custom functions with standard library equivalent
This commit is contained in:
parent
ec64990c98
commit
a1d860e0ef
2 changed files with 6 additions and 19 deletions
|
|
@ -20,6 +20,7 @@ package common
|
|||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
)
|
||||
|
|
@ -27,10 +28,10 @@ import (
|
|||
// FromHex returns the bytes represented by the hexadecimal string s.
|
||||
// s may be prefixed with "0x".
|
||||
func FromHex(s string) []byte {
|
||||
if has0xPrefix(s) {
|
||||
if len(s) >= 2 && strings.HasPrefix(strings.ToLower(s), "0x") {
|
||||
s = s[2:]
|
||||
}
|
||||
if len(s)%2 == 1 {
|
||||
if len(s)&1 == 1 {
|
||||
s = "0" + s
|
||||
}
|
||||
return Hex2Bytes(s)
|
||||
|
|
@ -47,27 +48,13 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
|
|||
return
|
||||
}
|
||||
|
||||
// has0xPrefix validates str begins with '0x' or '0X'.
|
||||
func has0xPrefix(str string) bool {
|
||||
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
|
||||
}
|
||||
|
||||
// isHexCharacter returns bool of c being a valid hexadecimal.
|
||||
func isHexCharacter(c byte) bool {
|
||||
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
|
||||
}
|
||||
|
||||
// isHex validates whether each byte is valid hexadecimal string.
|
||||
func isHex(str string) bool {
|
||||
if len(str)%2 != 0 {
|
||||
return false
|
||||
}
|
||||
for _, c := range []byte(str) {
|
||||
if !isHexCharacter(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
_, err := hex.DecodeString(str)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Bytes2Hex returns the hexadecimal encoding of d.
|
||||
|
|
|
|||
|
|
@ -231,7 +231,7 @@ func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }
|
|||
// IsHexAddress verifies whether a string can represent a valid hex-encoded
|
||||
// Ethereum address or not.
|
||||
func IsHexAddress(s string) bool {
|
||||
if has0xPrefix(s) {
|
||||
if len(s) >= 2 && strings.HasPrefix(strings.ToLower(s), "0x") {
|
||||
s = s[2:]
|
||||
}
|
||||
return len(s) == 2*AddressLength && isHex(s)
|
||||
|
|
|
|||
Loading…
Reference in a new issue