common: Improve IsHex and IsHexAddress & add tests#15551
Conversation
There was a problem hiding this comment.
The only use of IsHex is in IsHexAddress, also in package common. I think it would be best to delete IsHex and improve IsHexAddress instead. Bonus points if you can do it without a regular expression ;)
|
I have no experience with regular expressions in Go performance-wise. Are
they bad?
I will try. An address without the `0x` prefix should also be considered
valid, right?
…On 27 Nov 2017 15:34, "Felix Lange" ***@***.***> wrote:
***@***.**** commented on this pull request.
------------------------------
In common/bytes.go
<#15551 (comment)>
:
> func IsHex(str string) bool {
- l := len(str)
- return l >= 4 && l%2 == 0 && str[0:2] == "0x"
+ return hexRegex.MatchString(str)
}
The only use of IsHex is in IsHexAddress, also in package common. I think
it would be best to delete IsHex and improve IsHexAddress instead. Bonus
points if you can do it without a regular expression ;)
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<#15551 (review)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AA0F3Gj9RGtLEayV5YZuIqf-yw3grX2qks5s6shqgaJpZM4QpsoN>
.
|
|
Yes |
|
Regular expressions aren't bad, but package regexp is big and it's nice to avoid using it whenever possible. |
|
|
Hmm, so what this tells me is that we're not that far away from removing the common -> regexp dependency ;) |
7497bf2 to
8360ce3
Compare
|
@fjl Updated. Also improved IsHexAddress and added some tests for that. |
|
(That switch statement there is copied from Go's |
643f3cb to
25abdcb
Compare
There was a problem hiding this comment.
Please remove blank lines in this function.
There was a problem hiding this comment.
Please use for _, c := range []byte(src) because src is otherwise unused.
There was a problem hiding this comment.
Please use a boolean expression instead of switch.
There was a problem hiding this comment.
The switch is taken from the hex package. I think it's more readable. If you insist, I could change it...
There was a problem hiding this comment.
This could be s = s[2:] to avoid repeating the check expression.
Also unexport IsHex, HasHexPrefix because IsHexAddress is the only caller.
| return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') | ||
| } | ||
|
|
||
| func isHex(str string) bool { |
There was a problem hiding this comment.
This changes the semantics of IsHex/isHex. Previously, it expected a 0x-prefixed string, now it expects no prefix. That's fine, though, since it's internal we know it's not used anywhere where it will break anything.
There was a problem hiding this comment.
The only use is in IsHexAddress, which already checks for the prefix ;)
|
Great! |
Fixes #15550.