From 238036a861f0febf6c7fbf54ddaeee5c7d4175c9 Mon Sep 17 00:00:00 2001 From: Jorropo Date: Sun, 17 Mar 2024 04:33:22 +0100 Subject: [PATCH] Add nothing matcher --- patterns.go | 23 +++++++++++++++++++++++ patterns_test.go | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/patterns.go b/patterns.go index f082802..b0ff8f9 100644 --- a/patterns.go +++ b/patterns.go @@ -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 "" +} diff --git a/patterns_test.go b/patterns_test.go index 2a74c0c..c845d9b 100644 --- a/patterns_test.go +++ b/patterns_test.go @@ -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()