diff --git a/ipv4/range.go b/ipv4/range.go index 271448f..358d71f 100644 --- a/ipv4/range.go +++ b/ipv4/range.go @@ -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 diff --git a/ipv4/range_test.go b/ipv4/range_test.go index 07e1342..b57b270 100644 --- a/ipv4/range_test.go +++ b/ipv4/range_test.go @@ -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) + }) + } +}