Unverified Commit f512d0e0 authored by Steven Allen's avatar Steven Allen Committed by GitHub

Merge pull request #70 from multiformats/feat/zero-alloc-to-ip

feat: zero-alloc ToIP
parents e68f4d63 8838e2aa
......@@ -11,6 +11,7 @@ import (
)
var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion")
var errNotIP = fmt.Errorf("multiaddr does not start with an IP address")
// FromNetAddr converts a net.Addr type to a Multiaddr.
func FromNetAddr(a net.Addr) (ma.Multiaddr, error) {
......@@ -100,20 +101,22 @@ func FromIP(ip net.IP) (ma.Multiaddr, error) {
// ToIP converts a Multiaddr to a net.IP when possible
func ToIP(addr ma.Multiaddr) (net.IP, error) {
_, network, ip, _, hostname, err := dialArgComponents(addr)
if err != nil {
return nil, err
}
if hostname {
return nil, fmt.Errorf("non IP Multiaddr: %s %s", network, ip)
var ip net.IP
ma.ForEach(addr, func(c ma.Component) bool {
switch c.Protocol().Code {
case ma.P_IP6ZONE:
// we can't return these anyways.
return true
case ma.P_IP6, ma.P_IP4:
ip = net.IP(c.RawValue())
return false
}
switch network {
case "ip", "ip4", "ip6", "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6":
return net.ParseIP(ip), nil
default:
return nil, fmt.Errorf("non IP Multiaddr: %s %s", network, ip)
return false
})
if ip == nil {
return nil, errNotIP
}
return ip, nil
}
// DialArgs is a convenience function that returns network and address as
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment