common: improve IsHexAddress and add tests (#15551)

Also unexport isHex, hasHexPrefix because IsHexAddress is the only caller.

Fixes #15550
This commit is contained in:
Steven Roose
2017-12-04 19:34:15 +01:00
committed by Felix Lange
parent 1d06e41f04
commit afb8154eab
4 changed files with 65 additions and 28 deletions

View File

@ -17,9 +17,7 @@
// Package common contains various helper functions.
package common
import (
"encoding/hex"
)
import "encoding/hex"
func ToHex(b []byte) string {
hex := Bytes2Hex(b)
@ -55,14 +53,24 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
return
}
func HasHexPrefix(str string) bool {
l := len(str)
return l >= 2 && str[0:2] == "0x"
func hasHexPrefix(str string) bool {
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
}
func IsHex(str string) bool {
l := len(str)
return l >= 4 && l%2 == 0 && str[0:2] == "0x"
func isHexCharacter(c byte) bool {
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
}
func isHex(str string) bool {
if len(str)%2 != 0 {
return false
}
for _, c := range []byte(str) {
if !isHexCharacter(c) {
return false
}
}
return true
}
func Bytes2Hex(d []byte) string {