From d61fb4996f2937e8eb30627be9818bee71361508 Mon Sep 17 00:00:00 2001 From: vodkaslime <646329483@qq.com> Date: Mon, 26 Sep 2022 13:36:27 +0800 Subject: [PATCH] separately check if a pattern is wild --- wildcard.go | 20 +++++++++++++++---- wildcard_test.go | 51 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/wildcard.go b/wildcard.go index c71e089..dc4c80b 100644 --- a/wildcard.go +++ b/wildcard.go @@ -1,7 +1,5 @@ package wildcard -import "strings" - type Matcher struct { S byte M byte @@ -14,6 +12,21 @@ func NewMatcher() *Matcher { } } +func (m *Matcher) isWildPattern(pattern string) bool { + for i := range pattern { + c := pattern[i] + if c == m.M { + return true + } + + if c == m.S { + return true + } + } + + return false +} + func (m *Matcher) Match(pattern string, s string) (bool, error) { // Edge cases. if pattern == string(m.M) { @@ -29,8 +42,7 @@ func (m *Matcher) Match(pattern string, s string) (bool, error) { // If pattern does not contain wildcard chars, just compare the strings // to avoid extra memory allocation. - if !strings.Contains(pattern, string(m.M)) && - !strings.Contains(pattern, string(m.S)) { + if !m.isWildPattern(pattern) { return pattern == s, nil } diff --git a/wildcard_test.go b/wildcard_test.go index dd2f5ac..97ed8ec 100644 --- a/wildcard_test.go +++ b/wildcard_test.go @@ -6,15 +6,60 @@ import ( "github.com/stretchr/testify/assert" ) -type testCase struct { +type wildPatternTestCase struct { + p string + m bool +} + +type matchTestCase struct { p string s string m bool } +func TestIsWildPattern(t *testing.T) { + testCases1 := []wildPatternTestCase{ + {"*", true}, + {"**", true}, + {"*?", true}, + {"?", true}, + {".", false}, + {"a", false}, + {"a?c", true}, + } + + m1 := NewMatcher() + for _, tc := range testCases1 { + b := m1.isWildPattern(tc.p) + if !assert.Equal(t, b, tc.m) { + println(tc.p, tc.m) + } + } + + testCases2 := []wildPatternTestCase{ + {"*", true}, + {"**", true}, + {"*.", true}, + {"?", false}, + {".", true}, + {"a", false}, + {"a.c", true}, + } + + m2 := NewMatcher() + m2.S = '.' + for _, tc := range testCases2 { + b := m2.isWildPattern(tc.p) + if !assert.Equal(t, b, tc.m) { + println(tc.p, tc.m) + } + } + +} + func TestMatch(t *testing.T) { - testCases1 := []testCase{ + testCases1 := []matchTestCase{ {"", "", true}, {"*", "", true}, {"?", "", false}, @@ -43,7 +88,7 @@ func TestMatch(t *testing.T) { m2 := NewMatcher() m2.S = '.' - testCases2 := []testCase{ + testCases2 := []matchTestCase{ {"", "", true}, {"*", "", true}, {".", "", false},