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 ( ...@@ -11,6 +11,7 @@ import (
) )
var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion") 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. // FromNetAddr converts a net.Addr type to a Multiaddr.
func FromNetAddr(a net.Addr) (ma.Multiaddr, error) { func FromNetAddr(a net.Addr) (ma.Multiaddr, error) {
...@@ -100,20 +101,22 @@ func FromIP(ip net.IP) (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 // ToIP converts a Multiaddr to a net.IP when possible
func ToIP(addr ma.Multiaddr) (net.IP, error) { func ToIP(addr ma.Multiaddr) (net.IP, error) {
_, network, ip, _, hostname, err := dialArgComponents(addr) var ip net.IP
if err != nil { ma.ForEach(addr, func(c ma.Component) bool {
return nil, err switch c.Protocol().Code {
} case ma.P_IP6ZONE:
// we can't return these anyways.
if hostname { return true
return nil, fmt.Errorf("non IP Multiaddr: %s %s", network, ip) case ma.P_IP6, ma.P_IP4:
} ip = net.IP(c.RawValue())
switch network { return false
case "ip", "ip4", "ip6", "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6": }
return net.ParseIP(ip), nil return false
default: })
return nil, fmt.Errorf("non IP Multiaddr: %s %s", network, ip) if ip == nil {
return nil, errNotIP
} }
return ip, nil
} }
// DialArgs is a convenience function that returns network and address as // 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