Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions patterns.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,26 @@ func (p Base) partialMatch(pcs []ma.Protocol) (bool, []ma.Protocol) {
func (p Base) String() string {
return ma.ProtocolWithCode(int(p)).Name
}

// Nothing match an empty multiaddress, this let you write things like this:
//
// mafmt.And(mafmt.TCP, mafmt.Or(mafmt.Nothing, mafmt.Base(ma.P_TLS)))
//
// For a matcher which accepts tcp maddrs with an optional TLS suffix.
var Nothing empty

var _ Pattern = empty{}

type empty struct{}

func (empty) Matches(a ma.Multiaddr) bool {
return len(a.Bytes()) == 0
}

func (empty) partialMatch(pcs []ma.Protocol) (bool, []ma.Protocol) {
return len(pcs) == 0, pcs
}

func (empty) String() string {
return ""
}
16 changes: 16 additions & 0 deletions patterns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,22 @@ func TestUnreliableGroup(t *testing.T) {
assertMismatches(t, Unreliable, TestVectors["IP"].Good, TestVectors["TCP"].Good, TestVectors["UTP"].Good, TestVectors["IPFS"].Good, TestVectors["QUIC"].Good)
}

func TestNothing(t *testing.T) {
matcher := And(TCP, Or(Nothing, Base(ma.P_TLS)))
good := TestVectors["TCP"].Good
good = good[:len(good):len(good)]
for _, v := range good {
good = append(good, v+"/tls")
}
bad := TestVectors["TCP"].Good
bad = bad[:len(bad):len(bad)]
for _, v := range bad {
bad = append(bad, v+"/tls")
}
assertMatches(t, matcher, good)
assertMismatches(t, Unreliable, bad)
}

func assertMatches(t *testing.T, p Pattern, args ...[]string) {
t.Helper()

Expand Down