From 382dc7d208cf30e0d992d2ff42dc5bba0860a32b Mon Sep 17 00:00:00 2001 From: Yair Slobodin Date: Wed, 11 Dec 2024 17:14:46 +0200 Subject: [PATCH] compare --- pkg/netset/ipblock.go | 23 +++++++++++++++-------- pkg/netset/ipblock_test.go | 5 +++-- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/pkg/netset/ipblock.go b/pkg/netset/ipblock.go index c618863..520a9cb 100644 --- a/pkg/netset/ipblock.go +++ b/pkg/netset/ipblock.go @@ -152,14 +152,21 @@ func (b *IPBlock) IsSingleIPAddress() bool { return b.ipRange.IsSingleNumber() } -// Smaller returns true if this ipblock is smaller than other ipblock, and false o.w -// smaller == this.firstIP is smaller than other.firstIP -// if this.firstIP is equal to other.firstIP, decide by the lastIP -func (b *IPBlock) Smaller(other *IPBlock) bool { - if b.ipRange.Min() == other.ipRange.Min() { - return b.ipRange.Max() < other.ipRange.Max() - } - return b.ipRange.Min() < other.ipRange.Min() +// 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 diff --git a/pkg/netset/ipblock_test.go b/pkg/netset/ipblock_test.go index 5ec8294..f8d9b21 100644 --- a/pkg/netset/ipblock_test.go +++ b/pkg/netset/ipblock_test.go @@ -80,8 +80,9 @@ func TestOps(t *testing.T) { require.Equal(t, ipb7, ipb7.FirstIPAddressObject()) - require.True(t, ipb5.Smaller(ipb6)) - require.True(t, ipb1.Smaller(ipb2)) + 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) {