Skip to content

Commit 334b79e

Browse files
move FilterAddrs here from go-addr-util
1 parent 18266e9 commit 334b79e

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

multiaddr.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,3 +184,19 @@ func (m *multiaddr) ValueForProtocol(code int) (value string, err error) {
184184
})
185185
return
186186
}
187+
188+
// FilterAddrs is a filter that removes certain addresses, according to the given filters.
189+
// If all filters return true, the address is kept.
190+
func FilterAddrs(a []Multiaddr, filters ...func(Multiaddr) bool) []Multiaddr {
191+
b := make([]Multiaddr, 0, len(a))
192+
for _, addr := range a {
193+
good := true
194+
for _, filter := range filters {
195+
good = good && filter(addr)
196+
}
197+
if good {
198+
b = append(b, addr)
199+
}
200+
}
201+
return b
202+
}

multiaddr_test.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"testing"
99
"time"
1010

11+
"github.com/stretchr/testify/require"
12+
1113
"github.com/ipfs/go-cid"
1214
mh "github.com/multiformats/go-multihash"
1315
)
@@ -226,7 +228,7 @@ func TestStringToBytes(t *testing.T) {
226228
t.Error("failed to decode hex", h)
227229
}
228230

229-
//t.Log("196", h, []byte(b1))
231+
// t.Log("196", h, []byte(b1))
230232

231233
b2, err := stringToBytes(s)
232234
if err != nil {
@@ -739,3 +741,24 @@ func TestComponentJSONMarshaler(t *testing.T) {
739741
t.Error("expected equal components in circular marshaling test")
740742
}
741743
}
744+
745+
func TestFilterAddrs(t *testing.T) {
746+
bad := []Multiaddr{
747+
newMultiaddr(t, "/ip6/fe80::1/tcp/1234"),
748+
newMultiaddr(t, "/ip6/fe80::100/tcp/1234"),
749+
}
750+
good := []Multiaddr{
751+
newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234"),
752+
newMultiaddr(t, "/ip4/1.1.1.1/tcp/999"),
753+
newMultiaddr(t, "/ip4/1.2.3.4/udp/1234/utp"),
754+
}
755+
goodAndBad := append(good, bad...)
756+
757+
filter := func(addr Multiaddr) bool {
758+
return addr.Protocols()[0].Code == P_IP4
759+
}
760+
761+
require.Empty(t, FilterAddrs(bad, filter))
762+
require.ElementsMatch(t, FilterAddrs(good, filter), good)
763+
require.ElementsMatch(t, FilterAddrs(goodAndBad, filter), good)
764+
}

0 commit comments

Comments
 (0)