Skip to content

Commit

Permalink
added AsCidr method (#78)
Browse files Browse the repository at this point in the history
* added AsCidr method

* fixed doc
  • Loading branch information
YairSlobodin1 authored Oct 22, 2024
1 parent c7a61f7 commit be1b3fb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/netset/ipblock.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,16 @@ func cidrToInterval(cidr string) (interval.Interval, error) {
return interval.New(int64(startNum), int64(endNum)), nil
}

// AsCidr returns the CIDR string of this IPBlock object, if it contains exactly one CIDR,
// otherwise it returns an error
func (b *IPBlock) AsCidr() (string, error) {
cidrList := b.ToCidrList()
if len(cidrList) != 1 {
return "", fmt.Errorf("ipblock contains %d cidrs", len(cidrList))
}
return cidrList[0], nil
}

// ToCidrList returns a list of CIDR strings for this IPBlock object
func (b *IPBlock) ToCidrList() []string {
var cidrList []string
Expand Down
9 changes: 9 additions & 0 deletions pkg/netset/ipblock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ func TestConversions(t *testing.T) {
require.Equal(t, ipRange, toPrint[0])

require.Equal(t, "", ipb1.ToIPAddressString())

_, err = ipb1.AsCidr()
require.NotNil(t, err)

cidr := "5.2.1.0/24"
ipb3, _ := netset.IPBlockFromCidr(cidr)
str, err := ipb3.AsCidr()
require.Nil(t, err)
require.Equal(t, str, cidr)
}

func TestDisjointIPBlocks(t *testing.T) {
Expand Down

0 comments on commit be1b3fb

Please sign in to comment.