mirror of
https://github.com/logos-messaging/go-multiaddr.git
synced 2026-01-02 21:13:12 +00:00
move FilterAddrs here from go-addr-util
This commit is contained in:
parent
18266e9710
commit
334b79e5a9
16
multiaddr.go
16
multiaddr.go
@ -184,3 +184,19 @@ func (m *multiaddr) ValueForProtocol(code int) (value string, err error) {
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// FilterAddrs is a filter that removes certain addresses, according to the given filters.
|
||||
// If all filters return true, the address is kept.
|
||||
func FilterAddrs(a []Multiaddr, filters ...func(Multiaddr) bool) []Multiaddr {
|
||||
b := make([]Multiaddr, 0, len(a))
|
||||
for _, addr := range a {
|
||||
good := true
|
||||
for _, filter := range filters {
|
||||
good = good && filter(addr)
|
||||
}
|
||||
if good {
|
||||
b = append(b, addr)
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@ -8,6 +8,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
mh "github.com/multiformats/go-multihash"
|
||||
)
|
||||
@ -226,7 +228,7 @@ func TestStringToBytes(t *testing.T) {
|
||||
t.Error("failed to decode hex", h)
|
||||
}
|
||||
|
||||
//t.Log("196", h, []byte(b1))
|
||||
// t.Log("196", h, []byte(b1))
|
||||
|
||||
b2, err := stringToBytes(s)
|
||||
if err != nil {
|
||||
@ -739,3 +741,24 @@ func TestComponentJSONMarshaler(t *testing.T) {
|
||||
t.Error("expected equal components in circular marshaling test")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterAddrs(t *testing.T) {
|
||||
bad := []Multiaddr{
|
||||
newMultiaddr(t, "/ip6/fe80::1/tcp/1234"),
|
||||
newMultiaddr(t, "/ip6/fe80::100/tcp/1234"),
|
||||
}
|
||||
good := []Multiaddr{
|
||||
newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234"),
|
||||
newMultiaddr(t, "/ip4/1.1.1.1/tcp/999"),
|
||||
newMultiaddr(t, "/ip4/1.2.3.4/udp/1234/utp"),
|
||||
}
|
||||
goodAndBad := append(good, bad...)
|
||||
|
||||
filter := func(addr Multiaddr) bool {
|
||||
return addr.Protocols()[0].Code == P_IP4
|
||||
}
|
||||
|
||||
require.Empty(t, FilterAddrs(bad, filter))
|
||||
require.ElementsMatch(t, FilterAddrs(good, filter), good)
|
||||
require.ElementsMatch(t, FilterAddrs(goodAndBad, filter), good)
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user