Updates RangeSize func and tests for IPv6.

This commit is contained in:
Daneyon Hansen 2017-06-15 16:15:38 -07:00
parent e339400f6f
commit 3f293e2fe6
2 changed files with 34 additions and 11 deletions

View File

@ -263,8 +263,8 @@ func calculateIPOffset(base *big.Int, ip net.IP) int {
// RangeSize returns the size of a range in valid addresses. // RangeSize returns the size of a range in valid addresses.
func RangeSize(subnet *net.IPNet) int64 { func RangeSize(subnet *net.IPNet) int64 {
ones, bits := subnet.Mask.Size() ones, bits := subnet.Mask.Size()
if (bits - ones) >= 31 { if bits == 32 && (bits-ones) >= 31 || bits == 128 && (bits-ones) >= 63 {
panic("masks greater than 31 bits are not supported") return 0
} }
max := int64(1) << uint(bits-ones) max := int64(1) << uint(bits-ones)
return max return max

View File

@ -166,18 +166,41 @@ func TestAllocateSmall(t *testing.T) {
} }
func TestRangeSize(t *testing.T) { func TestRangeSize(t *testing.T) {
testCases := map[string]int64{ testCases := []struct {
"192.168.1.0/24": 256, name string
"192.168.1.0/32": 1, cidr string
"192.168.1.0/31": 2, addrs int64
}{
{
name: "supported IPv4 cidr",
cidr: "192.168.1.0/24",
addrs: 256,
},
{
name: "unsupported IPv4 cidr",
cidr: "192.168.1.0/1",
addrs: 0,
},
{
name: "supported IPv6 cidr",
cidr: "2001:db8::/98",
addrs: 1073741824,
},
{
name: "unsupported IPv6 mask",
cidr: "2001:db8::/65",
addrs: 0,
},
} }
for k, v := range testCases {
_, cidr, err := net.ParseCIDR(k) for _, tc := range testCases {
_, cidr, err := net.ParseCIDR(tc.cidr)
if err != nil { if err != nil {
t.Fatal(err) t.Errorf("failed to parse cidr for test %s, unexpected error: '%s'", tc.name, err)
} }
if size := RangeSize(cidr); size != v { if size := RangeSize(cidr); size != tc.addrs {
t.Errorf("%s should have a range size of %d, got %d", k, v, size) t.Errorf("test %s failed. %s should have a range size of %d, got %d",
tc.name, tc.cidr, tc.addrs, size)
} }
} }
} }