Skip to content

Commit

Permalink
netutil: imp
Browse files Browse the repository at this point in the history
  • Loading branch information
Mizzick committed Jul 18, 2024
1 parent 68c7854 commit 5e322ab
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
5 changes: 5 additions & 0 deletions netutil/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,8 @@ func ValidateIP(ip net.IP) (err error) {
}
}
}

// IsValidIPString returns true if ip is a valid IPv4 or IPv6 address.
func IsValidIPString(ip string) (ok bool) {
return net.ParseIP(ip) != nil
}
58 changes: 58 additions & 0 deletions netutil/ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,61 @@ func TestValidateIP(t *testing.T) {
})
}
}

func BenchmarkIsValidIPString(b *testing.B) {
benchCases := []struct {
want assert.BoolAssertionFunc
name string
in string
}{{
want: assert.True,
name: "success_ipv4",
in: testIPv4.String(),
}, {
want: assert.True,
name: "success_ipv6",
in: testIPv6.String(),
}, {
want: assert.False,
name: "error_nil",
in: "",
}, {
want: assert.False,
name: "error_empty",
in: net.IP{}.String(),
}, {
want: assert.False,
name: "error_bad",
in: net.IP{1, 2, 3}.String(),
}}

for _, bc := range benchCases {
b.Run(bc.name, func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
boolSink = netutil.IsValidIPString(bc.in)
}

bc.want(b, boolSink)
})
}

// Most recent results, on an MBP 14 with Apple M1 Pro chip:
//
// goos: darwin
// goarch: arm64
// pkg: github.com/AdguardTeam/golibs/netutil
// BenchmarkIsValidIPString
// BenchmarkIsValidIPString/success_ipv4
// BenchmarkIsValidIPString/success_ipv4-8 74761114 15.21 ns/op 0 B/op 0 allocs/op
// BenchmarkIsValidIPString/success_ipv6
// BenchmarkIsValidIPString/success_ipv6-8 35581647 33.86 ns/op 0 B/op 0 allocs/op
// BenchmarkIsValidIPString/error_nil
// BenchmarkIsValidIPString/error_nil-8 41771821 29.23 ns/op 48 B/op 1 allocs/op
// BenchmarkIsValidIPString/error_empty
// BenchmarkIsValidIPString/error_empty-8 39244113 30.94 ns/op 48 B/op 1 allocs/op
// BenchmarkIsValidIPString/error_bad
// BenchmarkIsValidIPString/error_bad-8 38729404 31.89 ns/op 48 B/op 1 allocs/op
}

0 comments on commit 5e322ab

Please sign in to comment.