Created
December 1, 2021 18:48
-
-
Save stokito/92c40ba2b70c5db775455ef65a304a95 to your computer and use it in GitHub Desktop.
Golang parse IPv4 to bytes array without unnecessary allocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// parseIPv4 fast path clone of net.ParseIP that don't wrap IPv4 into IPv6 array | |
func parseIPv4(s string) []byte { | |
var p [4]byte | |
for i := 0; i < 4; i++ { | |
octet, pos := dtoi(s) | |
p[i] = octet | |
if i < 3 { | |
s = s[pos+1:] | |
} | |
} | |
return p[:] | |
} | |
func dtoi(octetStr string) (n byte, pos int) { | |
n = 0 | |
for pos = 0; pos < len(octetStr); pos++ { | |
u := octetStr[pos] | |
if u == '.' { | |
break | |
} | |
n = n*10 + (u - '0') | |
} | |
return n, pos | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment