Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added AsCidr method #78

Merged
merged 4 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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