From d4ce4cb249581363ae573157898db9f904c971fa Mon Sep 17 00:00:00 2001 From: Chad Robinson Date: Sat, 25 Sep 2021 09:55:09 -0700 Subject: [PATCH] small improvement to NewNetBetween (#6) --- iplib_bench_test.go | 8 ++++++++ net.go | 35 +++++++++++++++-------------------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/iplib_bench_test.go b/iplib_bench_test.go index a0ff2dd..8e8e997 100644 --- a/iplib_bench_test.go +++ b/iplib_bench_test.go @@ -209,6 +209,14 @@ func BenchmarkNewNetBetween_v4(b *testing.B) { } } +func BenchmarkNewNetBetween_v6(b *testing.B) { + ipa, _, _ := net.ParseCIDR("::") + ipb, _, _ := net.ParseCIDR("ffff::") + for i := 0; i < b.N; i++ { + _, _, _ = NewNetBetween(ipa, ipb) + } +} + func BenchmarkNet6_nextIPWithinHostmask(b *testing.B) { var xip = net.IP{32, 1, 13, 184, 133, 163, 0, 0, 0, 0, 138, 46, 3, 112, 115, 52} hm := NewHostMask(8) diff --git a/net.go b/net.go index e8ad8ac..689e588 100644 --- a/net.go +++ b/net.go @@ -44,26 +44,7 @@ func NewNetBetween(a, b net.IP) (Net, bool, error) { return nil, false, ErrNoValidRange } - maskMax := 128 - if EffectiveVersion(a) == 4 { - maskMax = 32 - } - - ipa := NextIP(a) - ipb := PreviousIP(b) - for i := 1; i <= maskMax; i++ { - xnet := NewNet(ipa, i) - - va := CompareIPs(xnet.FirstAddress(), ipa) - vb := CompareIPs(xnet.LastAddress(), ipb) - if va >= 0 && vb < 0 { - return xnet, false, nil - } - if va == 0 && vb == 0 { - return xnet, true, nil - } - } - return nil, false, ErrNoValidRange + return fitNetworkBetween(NextIP(a), PreviousIP(b), 1) } // ByNet implements sort.Interface for iplib.Net based on the @@ -118,3 +99,17 @@ func ParseCIDR(s string) (net.IP, Net, error) { return ip, NewNet6(ip, masklen, 0), err } + +func fitNetworkBetween(a, b net.IP, mask int) (Net, bool, error) { + xnet := NewNet(a, mask) + + va := CompareIPs(xnet.FirstAddress(), a) + vb := CompareIPs(xnet.LastAddress(), b) + if va >= 0 && vb < 0 { + return xnet, false, nil + } + if va == 0 && vb == 0 { + return xnet, true, nil + } + return fitNetworkBetween(a, b, mask + 1) +} \ No newline at end of file