Skip to content
This repository has been archived by the owner on Sep 9, 2022. It is now read-only.

Commit

Permalink
chore: better address parsing
Browse files Browse the repository at this point in the history
Use ma.SplitFunc instead of splitting the entire multiaddr and comparing bytes.
This avoids a bunch of unnecessary allocation and copying.
  • Loading branch information
Stebalien committed Sep 18, 2019
1 parent cd89397 commit a8e2ae4
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,25 @@ func (d *RelayTransport) Dial(ctx context.Context, a ma.Multiaddr, p peer.ID) (t
}

func (r *Relay) Dial(ctx context.Context, a ma.Multiaddr, p peer.ID) (*Conn, error) {
if !r.Matches(a) {
// split /a/p2p-circuit/b into (/a, /p2p-circuit/b)
relayaddr, destaddr := ma.SplitFunc(a, func(c ma.Component) bool {
return c.Protocol().Code == P_CIRCUIT
})

// If the address contained no /p2p-circuit part, the second part is nil.
if destaddr == nil {
return nil, fmt.Errorf("%s is not a relay address", a)
}
parts := ma.Split(a)

spl := ma.Cast(ma.CodeToVarint(P_CIRCUIT))

var relayaddr, destaddr ma.Multiaddr
for i, p := range parts {
if p.Equal(spl) {
relayaddr = ma.Join(parts[:i]...)
destaddr = ma.Join(parts[i+1:]...)
break
}
}
// Strip the /p2p-circuit prefix from the destaddr.
_, destaddr = ma.SplitFirst(destaddr)

dinfo := &pstore.PeerInfo{ID: p, Addrs: []ma.Multiaddr{}}
if len(destaddr.Bytes()) > 0 {
if destaddr != nil {
dinfo.Addrs = append(dinfo.Addrs, destaddr)
}

if len(relayaddr.Bytes()) == 0 {
if relayaddr != nil {
// unspecific relay address, try dialing using known hop relays
return r.tryDialRelays(ctx, *dinfo)
}
Expand Down

0 comments on commit a8e2ae4

Please sign in to comment.