Skip to content

Commit

Permalink
Add nothing matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
Jorropo committed Mar 17, 2024
1 parent e8647c6 commit 238036a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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

Check warning on line 190 in patterns.go

View check run for this annotation

Codecov / codecov/patch

patterns.go#L189-L190

Added lines #L189 - L190 were not covered by tests
}

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

0 comments on commit 238036a

Please sign in to comment.