Skip to content

Commit

Permalink
small improvement to NewNetBetween (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
c-robinson authored Sep 25, 2021
1 parent 0fd801a commit d4ce4cb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 20 deletions.
8 changes: 8 additions & 0 deletions iplib_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 15 additions & 20 deletions net.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}

0 comments on commit d4ce4cb

Please sign in to comment.