-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparse_ip4_test.go
70 lines (62 loc) · 1.57 KB
/
parse_ip4_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"encoding/binary"
"net"
"testing"
)
// IPv4StrToInt converts a string containing an IPv4 address to its uint32 representation.
var testCases = []struct {
input string
expected uint32
}{
{"0.0.0.0", 0x00000000},
{"255.255.255.255", 0xFFFFFFFF},
{"192.168.0.1", 0xC0A80001},
{"1.1.1.1", 0x01010101},
{"127.0.0.1", 0x7F000001},
{"256.0.0.1", 0xFFFFFFFF},
{"255.255.255.256", 0xFFFFFFFF},
{"255.255.255", 0xFFFFFFFF},
{"255.255.255.255.255", 0xFFFFFFFF},
{"255..255.255", 0xFFFFFFFF},
{"255.255..255", 0xFFFFFFFF},
{"255.255.255.", 0xFFFFFFFF},
{"", 0xFFFFFFFF},
}
// IPv4StrToInt converts a string containing an IPv4 address to its uint32 representation.
// The implementation is based on the net.ParseIP function.
func ip2int(s string) uint32 {
ip := net.ParseIP(s)
if ip == nil {
return 0xFFFFFFFF
}
if len(ip) == 16 {
return binary.BigEndian.Uint32(ip[12:16])
}
return binary.BigEndian.Uint32(ip)
}
// Benchmark_ip2int benchmarks the ip2int function.
func Benchmark_ip2int(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, ip := range testCases {
ip2int(ip.input)
}
}
}
// Benchmark_parseIp4 benchmarks the IPv4StrToInt function.
func Benchmark_parseIp4(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, ip := range testCases {
IPv4StrToInt(ip.input)
}
}
}
// TestIPv4StrToInt tests the IPv4StrToInt function.
func TestIPv4StrToInt(t *testing.T) {
for _, tc := range testCases {
result := IPv4StrToInt(tc.input)
if result != tc.expected {
t.Errorf("ipv4StrToInt(%q) = %x; want %x", tc.input, result, tc.expected)
}
}
}