Skip to content
This repository was archived by the owner on Oct 5, 2021. It is now read-only.

Commit f512d0e

Browse files
authored
Merge pull request #70 from multiformats/feat/zero-alloc-to-ip
feat: zero-alloc ToIP
2 parents e68f4d6 + 8838e2a commit f512d0e

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

convert.go

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
)
1212

1313
var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion")
14+
var errNotIP = fmt.Errorf("multiaddr does not start with an IP address")
1415

1516
// FromNetAddr converts a net.Addr type to a Multiaddr.
1617
func FromNetAddr(a net.Addr) (ma.Multiaddr, error) {
@@ -100,20 +101,22 @@ func FromIP(ip net.IP) (ma.Multiaddr, error) {
100101

101102
// ToIP converts a Multiaddr to a net.IP when possible
102103
func ToIP(addr ma.Multiaddr) (net.IP, error) {
103-
_, network, ip, _, hostname, err := dialArgComponents(addr)
104-
if err != nil {
105-
return nil, err
106-
}
107-
108-
if hostname {
109-
return nil, fmt.Errorf("non IP Multiaddr: %s %s", network, ip)
110-
}
111-
switch network {
112-
case "ip", "ip4", "ip6", "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6":
113-
return net.ParseIP(ip), nil
114-
default:
115-
return nil, fmt.Errorf("non IP Multiaddr: %s %s", network, ip)
104+
var ip net.IP
105+
ma.ForEach(addr, func(c ma.Component) bool {
106+
switch c.Protocol().Code {
107+
case ma.P_IP6ZONE:
108+
// we can't return these anyways.
109+
return true
110+
case ma.P_IP6, ma.P_IP4:
111+
ip = net.IP(c.RawValue())
112+
return false
113+
}
114+
return false
115+
})
116+
if ip == nil {
117+
return nil, errNotIP
116118
}
119+
return ip, nil
117120
}
118121

119122
// DialArgs is a convenience function that returns network and address as

0 commit comments

Comments
 (0)