AdGuardDNS/internal/agdnet/prefixaddr.go

36 lines
968 B
Go
Raw Normal View History

2023-09-06 08:22:07 +03:00
package agdnet
import (
"fmt"
2024-01-04 19:22:32 +03:00
"net"
2023-09-06 08:22:07 +03:00
"net/netip"
)
2024-01-04 19:22:32 +03:00
// PrefixNetAddr is a wrapper around netip.Prefix that makes it a [net.Addr].
type PrefixNetAddr struct {
Prefix netip.Prefix
Net string
Port uint16
}
// type check
var _ net.Addr = (*PrefixNetAddr)(nil)
// String implements the [net.Addr] interface for *PrefixNetAddr. It returns
// either a simple IP:port address or one with the prefix length appended after
// a slash, depending on whether or not subnet is a single-address subnet. This
// is done to make using the IP:port part easier to split off using functions
// like [strings.Cut].
func (addr *PrefixNetAddr) String() (n string) {
p := addr.Prefix
addrPort := netip.AddrPortFrom(p.Addr(), addr.Port)
if p.IsSingleIP() {
2023-09-06 08:22:07 +03:00
return addrPort.String()
}
2024-01-04 19:22:32 +03:00
return fmt.Sprintf("%s/%d", addrPort, p.Bits())
2023-09-06 08:22:07 +03:00
}
2024-01-04 19:22:32 +03:00
// Network implements the [net.Addr] interface for *PrefixNetAddr.
func (addr *PrefixNetAddr) Network() (n string) { return addr.Net }