Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add nothing matcher #35

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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) 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
Loading