Skip to content

Instantly share code, notes, and snippets.

@svolobuev
Created May 30, 2019 08:15
Show Gist options
  • Save svolobuev/8120f155deb21ed02682a20c18a21a6b to your computer and use it in GitHub Desktop.
Save svolobuev/8120f155deb21ed02682a20c18a21a6b to your computer and use it in GitHub Desktop.
$ go test -bench=.
goos: darwin
goarch: amd64
pkg: github.com/svolobuev/fox/ip
BenchmarkToUint32-4 10000000 118 ns/op 16 B/op 1 allocs/op
BenchmarkToString-4 20000000 56.7 ns/op 16 B/op 1 allocs/op
PASS
ok github.com/svolobuev/fox/ip 2.519s
package ip
import (
"encoding/binary"
"errors"
"net"
)
func ToUint32(input string) (uint32, error) {
ip := net.ParseIP(input)
if ip == nil {
return 0, errors.New("wrong input format, input like as ip: 127.0.01, 10.10.242.125")
}
ip = ip.To4()
return binary.BigEndian.Uint32(ip), nil
}
func ToString(input uint32) string {
ipByte := make([]byte, 4)
binary.BigEndian.PutUint32(ipByte, input)
return net.IP(ipByte).String()
}
package ip
import (
"testing"
)
const ipAsString = "127.0.0.1"
const ipAsLong = 2130706433
func TestToUint32(t *testing.T) {
ip, err := ToUint32(ipAsString)
if err != nil {
t.Error("Ip2Long error", err)
}
if ipAsLong != ip {
t.Errorf("Expected: %d from %s, but given %d", ipAsLong, ipAsString, ip)
}
}
func TestToString(t *testing.T) {
ip := ToString(ipAsLong)
if ipAsString != ip {
t.Errorf("Expected: %s from %d, but given %s", ipAsString, ipAsLong, ip)
}
}
func BenchmarkToUint32(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = ToUint32(ipAsString)
}
}
func BenchmarkToString(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = ToString(ipAsLong)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment