diff --git a/pkg/netset/ipblock.go b/pkg/netset/ipblock.go index 164a336..5950bce 100644 --- a/pkg/netset/ipblock.go +++ b/pkg/netset/ipblock.go @@ -152,6 +152,22 @@ func (b *IPBlock) IsSingleIPAddress() bool { return b.ipRange.IsSingleNumber() } +// Compare returns -1 if thisother, 0 o.w. +func (b *IPBlock) Compare(other *IPBlock) int { + switch { + case b.ipRange.Min() < other.ipRange.Min(): + return -1 + case b.ipRange.Min() > other.ipRange.Min(): + return 1 + case b.ipRange.Max() < other.ipRange.Max(): + return -1 + case b.ipRange.Max() > other.ipRange.Max(): + return 1 + default: + return 0 + } +} + // Split returns a set of IPBlock objects, each with a single range of ips func (b *IPBlock) Split() []*IPBlock { intervals := b.ipRange.Intervals() diff --git a/pkg/netset/ipblock_test.go b/pkg/netset/ipblock_test.go index 4763fb8..f8d9b21 100644 --- a/pkg/netset/ipblock_test.go +++ b/pkg/netset/ipblock_test.go @@ -42,12 +42,12 @@ func TestOps(t *testing.T) { intersect2 := minus.Intersect(intersect) require.True(t, intersect2.IsEmpty()) - ipb3, err := ipb2.NextIP() + ipb3, err := ipb2.NextIP() // ipb3 = 1.2.3.5 ipb4, _ := netset.IPBlockFromCidrOrAddress("1.2.3.5") require.Nil(t, err) require.Equal(t, ipb3, ipb4) - ipb5, err := ipb3.PreviousIP() + ipb5, err := ipb3.PreviousIP() // ipb5 = 1.2.3.4 require.Nil(t, err) require.Equal(t, ipb2, ipb5) @@ -79,6 +79,10 @@ func TestOps(t *testing.T) { require.False(t, t2) require.Equal(t, ipb7, ipb7.FirstIPAddressObject()) + + require.Equal(t, ipb5.Compare(ipb6), -1) + require.Equal(t, ipb2.Compare(ipb1), 1) + require.Equal(t, ipb3.Compare(ipb4), 0) } func TestConversions(t *testing.T) {