Skip to content

Commit

Permalink
Compare ipblock (#88)
Browse files Browse the repository at this point in the history
  • Loading branch information
YairSlobodin1 authored Dec 11, 2024
1 parent 2be185b commit 6a8d70f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
16 changes: 16 additions & 0 deletions pkg/netset/ipblock.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,22 @@ func (b *IPBlock) IsSingleIPAddress() bool {
return b.ipRange.IsSingleNumber()
}

// Compare returns -1 if this<other, 1 if this>other, 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()
Expand Down
8 changes: 6 additions & 2 deletions pkg/netset/ipblock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 6a8d70f

Please sign in to comment.