Skip to content

Commit

Permalink
implement NumPrefixes for IPv4 Range
Browse files Browse the repository at this point in the history
  • Loading branch information
ecbaldwin committed Jun 6, 2024
1 parent 2b7fdba commit 7241038
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
9 changes: 8 additions & 1 deletion ipv4/range.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,16 @@ func RangeFromAddresses(first, last Address) (r Range, empty bool) {
}, false
}

// NumPrefixes returns the number of prefixes of the given prefix length in
// this range.
func (me Range) NumPrefixes(length uint32) (count uint64, err error) {
return me.Set().NumPrefixes(length)
}

// NumAddresses returns the number of addresses in the range
func (me Range) NumAddresses() int64 {
return 1 + int64(me.last.ui-me.first.ui)
c, _ := me.NumPrefixes(32)
return int64(c)
}

// First returns the first address in the range
Expand Down
30 changes: 30 additions & 0 deletions ipv4/range_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,33 @@ func TestRangeAsMapKey(t *testing.T) {

assert.True(t, m[_r(_a("203.0.113.0"), _a("203.0.113.127"))])
}

func TestRangeNumPrefixes(t *testing.T) {
tests := []struct {
description string
r Range
length uint32
count uint64
error bool
}{
{
description: "simple",
r: _r(_a("203.0.113.0"), _a("203.0.114.0")),
length: 31,
count: 128,
}, {
description: "bonus",
r: _r(_a("203.0.113.0"), _a("203.0.114.0")),
length: 32,
count: 257,
},
}

for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
count, err := tt.r.NumPrefixes(tt.length)
assert.Equal(t, tt.error, err != nil)
assert.Equal(t, tt.count, count)
})
}
}

0 comments on commit 7241038

Please sign in to comment.