Skip to content

Commit

Permalink
fix bug: matching pattern like *head with string like head_hello will…
Browse files Browse the repository at this point in the history
… panic
  • Loading branch information
forrestjgq committed Feb 16, 2022
1 parent d30d557 commit 889ca1c
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 17 deletions.
35 changes: 18 additions & 17 deletions internal/util/wild_matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,44 +63,45 @@ func wildcmp(wild string, str string, questionMark byte) bool {
)

i := 0
for i < len(str) && wild[i] != '*' {
for i < len(str) && i < len(wild) && wild[i] != '*' {
if wild[i] != str[i] && wild[i] != questionMark {
return false
}
i++
}

j := i
for i < len(str) {
s := str[i]
w := wild[j]
wild = wild[i:]
str = str[i:]
for len(str) > 0 {
s := str[0]
w := uint8(0)
if len(wild) > 0 {
w = wild[0]
}
if w == '*' {
j++
if j == len(wild) {
wild = wild[1:]
if len(wild) == 0 {
return true
}
mp = wild[j:]
cp = str[i+1:]
mp = wild
cp = str[1:]
} else if w == s || w == questionMark {
i++
j++
str = str[1:]
wild = wild[1:]
} else {
wild = mp
j = 0

str = cp
if len(cp) > 0 {
cp = cp[1:]
}
i = 0
}
}

for j < len(wild) && wild[j] == '*' {
j++
for len(wild) > 0 && wild[0] == '*' {
wild = wild[1:]
}

return j >= len(wild)
return len(wild) == 0
}
func (w *WildcardMatcher) Wildcards() []string {
return w.wcs
Expand Down
77 changes: 77 additions & 0 deletions internal/util/wild_matcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package util

import "testing"

func TestWildMatcher(t *testing.T) {
m := NewWildcardMatcher("*decode*,*hello*", '?', true)
b := m.Match("this_is_a_decode_name")
if !b {
t.Fatalf("fail match")
}
b = m.Match("this_is_a_hello_name")
if !b {
t.Fatalf("fail match")
}
b = m.Match("this_is_a_name")
if b {
t.Fatalf("fail match")
}
b = m.Match("")
if b {
t.Fatalf("fail match")
}
b = m.Match("decode")
if !b {
t.Fatalf("fail match")
}
b = m.Match("hello")
if !b {
t.Fatalf("fail match")
}
b = m.Match("hellodecode")
if !b {
t.Fatalf("fail match")
}
b = m.Match("")
if b {
t.Fatalf("fail match")
}
}
func TestWildMatcherHead(t *testing.T) {
m := NewWildcardMatcher("*decode", '?', true)
b := m.Match("decode_name")
if b {
t.Fatalf("fail match")
}
b = m.Match("jgq_decode")
if !b {
t.Fatalf("fail match")
}
}
func TestWildMatcherTail(t *testing.T) {
m := NewWildcardMatcher("decode*", '?', true)
b := m.Match("decode_name")
if !b {
t.Fatalf("fail match")
}
b = m.Match("jgq_decode")
if b {
t.Fatalf("fail match")
}
}
func TestEmptyMatcher(t *testing.T) {
m := NewWildcardMatcher("", '?', false)
b := m.Match("")
if b {
t.Fatalf("fail match")
}
b = m.Match("hello")
if b {
t.Fatalf("fail match")
}
m = NewWildcardMatcher("", '?', true)
b = m.Match("")
if !b {
t.Fatalf("fail match")
}
}

0 comments on commit 889ca1c

Please sign in to comment.