rings: introduce PrefixToRange()

returning the beginning and end of a subnet

Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
2024-05-25 19:12:44 +00:00
parent 50436a320c
commit 3e90c7a30b
2 changed files with 120 additions and 0 deletions
+34
View File
@@ -41,3 +41,37 @@ func AddrToU32(addr netip.Addr) (v uint32, ok bool) {
return 0, false
}
// PrefixToRange returns the beginning and end of a
// [netip.Prefix] (aka CIDR or subnet).
func PrefixToRange(subnet netip.Prefix) (from, to netip.Addr, ok bool) {
var u uint32
addr := subnet.Addr()
if u, ok = AddrToU32(addr); ok {
bits := subnet.Bits()
switch {
case bits > 32, bits < 0:
// bad
case bits == 32:
// single
from, to, ok = addr, addr, true
default:
// subnet
shift := 32 - bits
m1 := uint32((1 << shift) - 1)
m0 := uint32(0xffffffff) & ^m1
u0 := u & m0
u1 := u0 + m1
ok = true
from = AddrFromU32(u0)
to = AddrFromU32(u1)
}
}
return from, to, ok
}