Files
jpictl/pkg/rings/decode.go
T
2024-05-28 14:58:41 +00:00

91 lines
1.9 KiB
Go

package rings
import (
"net/netip"
"darvaza.org/core"
)
// DecodeAddress ... TODO
//
// revive:disable:function-result-limit
func DecodeAddress(addr netip.Addr) (Ring, RegionID, ZoneID, uint) {
// revive:enable:function-result-limit
if addr.IsValid() {
if addr.Is4In6() {
addr = addr.Unmap()
}
if addr.Is4() {
a4 := addr.As4()
return unsafeDecodeAddress(a4[0], a4[1], a4[2], a4[3])
}
}
return InvalidRing, 0, 0, 0
}
// revive:disable:function-result-limit
func unsafeDecodeAddress(a, b, c, d byte) (Ring, RegionID, ZoneID, uint) {
// revive:enable:function-result-limit
switch {
case a != 10:
return InvalidRing, 0, 0, 0
case b&0xf0 != 0:
k := RingThree
r := RegionID(b >> 4)
n2 := uint(b & 0x0f)
n1 := uint(c)
n0 := uint(d)
n := n0 + n1<<8 + n2<<16
return k, r, 0, n
case b&0x0f != 0:
r := RegionID(b)
z := ZoneID(c >> 4)
k := core.IIf(z == 0, RingTwo, RingOne)
n1 := uint(c & 0x0f)
n0 := uint(d)
n := n0 + n1<<8
return k, r, z, n
default: // b == 0
k := RingZero
r := RegionID(c >> 4)
z := ZoneID(c & 0xf)
n := uint(d)
return k, r, z, n
}
}
// DecodeRingZeroAddress attempts to extract region, zone and node identifiers
// from a given ring 0 address.
//
// revive:disable:function-result-limit
func DecodeRingZeroAddress(addr netip.Addr) (RegionID, ZoneID, NodeID, bool) {
// revive:enable:function-result-limit
k, r, z, n := DecodeAddress(addr)
if k == RingZero {
return r, z, NodeID(n), true
}
return 0, 0, 0, false
}
// DecodeRingOneAddress attempts to extract region, zone and node identifiers
// from a given ring 1 address.
//
// revive:disable:function-result-limit
func DecodeRingOneAddress(addr netip.Addr) (RegionID, ZoneID, NodeID, bool) {
// revive:enable:function-result-limit
k, r, z, n := DecodeAddress(addr)
if k == RingOne {
return r, z, NodeID(n), true
}
return 0, 0, 0, false
}