rewrite value for protocols and add more tests
This commit is contained in:
parent
a581da3f8f
commit
ae64eb994b
21
multiaddr.go
21
multiaddr.go
|
@ -117,28 +117,15 @@ func (m *multiaddr) Decapsulate(o Multiaddr) Multiaddr {
|
|||
var ErrProtocolNotFound = fmt.Errorf("protocol not found in multiaddr")
|
||||
|
||||
func (m *multiaddr) ValueForProtocol(code int) (string, error) {
|
||||
protos := m.Protocols()
|
||||
found := -1
|
||||
index := 2
|
||||
|
||||
for i, p := range protos {
|
||||
if code == p.Code {
|
||||
for _, sub := range Split(m) {
|
||||
p := sub.Protocols()[0]
|
||||
if p.Code == code {
|
||||
if p.Size == 0 {
|
||||
return "", nil
|
||||
}
|
||||
found = i
|
||||
break
|
||||
} else {
|
||||
index += 2
|
||||
if p.Size == 0 {
|
||||
index--
|
||||
}
|
||||
return strings.Split(sub.String(), "/")[2], nil
|
||||
}
|
||||
}
|
||||
|
||||
if found == -1 {
|
||||
return "", ErrProtocolNotFound
|
||||
}
|
||||
|
||||
return strings.Split(m.String(), "/")[index], nil
|
||||
}
|
||||
|
|
|
@ -330,4 +330,15 @@ func TestGetValue(t *testing.T) {
|
|||
default:
|
||||
t.Fatalf("expected ErrProtocolNotFound but got: %s", err)
|
||||
}
|
||||
|
||||
a = newMultiaddr(t, "/ip4/0.0.0.0") // only one addr
|
||||
assertValueForProto(t, a, P_IP4, "0.0.0.0")
|
||||
|
||||
a = newMultiaddr(t, "/ip4/0.0.0.0/ip4/0.0.0.0/ip4/0.0.0.0") // same sub-addr
|
||||
assertValueForProto(t, a, P_IP4, "0.0.0.0")
|
||||
|
||||
a = newMultiaddr(t, "/ip4/0.0.0.0/udp/12345/utp") // ending in a no-value one.
|
||||
assertValueForProto(t, a, P_IP4, "0.0.0.0")
|
||||
assertValueForProto(t, a, P_UDP, "12345")
|
||||
assertValueForProto(t, a, P_UTP, "")
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue