Skip to content

Instantly share code, notes, and snippets.

@stokito
Created December 1, 2021 18:48
Show Gist options
  • Save stokito/92c40ba2b70c5db775455ef65a304a95 to your computer and use it in GitHub Desktop.
Save stokito/92c40ba2b70c5db775455ef65a304a95 to your computer and use it in GitHub Desktop.
Golang parse IPv4 to bytes array without unnecessary allocation
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