Skip to content

Commit c2f5341

Browse files
committed
Fix slowness with repetitive stars
1 parent 82db0ac commit c2f5341

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

match.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,16 @@ import "unicode/utf8"
1616
// '\\' c matches character c
1717
//
1818
func Match(str, pattern string) bool {
19-
if pattern == "*" {
20-
return true
21-
}
2219
return deepMatch(str, pattern)
2320
}
21+
2422
func deepMatch(str, pattern string) bool {
23+
if pattern == "*" {
24+
return true
25+
}
26+
for len(pattern) > 1 && pattern[0] == '*' && pattern[1] == '*' {
27+
pattern = pattern[1:]
28+
}
2529
for len(pattern) > 0 {
2630
if pattern[0] > 0x7f {
2731
return deepMatchRune(str, pattern)
@@ -52,6 +56,13 @@ func deepMatch(str, pattern string) bool {
5256
}
5357

5458
func deepMatchRune(str, pattern string) bool {
59+
if pattern == "*" {
60+
return true
61+
}
62+
for len(pattern) > 1 && pattern[0] == '*' && pattern[1] == '*' {
63+
pattern = pattern[1:]
64+
}
65+
5566
var sr, pr rune
5667
var srsz, prsz int
5768

match_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package match
33
import (
44
"fmt"
55
"math/rand"
6+
"strings"
67
"testing"
78
"time"
89
"unicode/utf8"
@@ -427,3 +428,17 @@ func BenchmarkUnicode(t *testing.B) {
427428
}
428429
}
429430
}
431+
432+
func TestLotsaStars(t *testing.T) {
433+
// This tests that a pattern with lots of stars will complete quickly.
434+
var str, pat string
435+
436+
str = `,**,,**,**,**,**,**,**,`
437+
pat = `,**********************************************{**",**,,**,**,` +
438+
`**,**,"",**,**,**,**,**,**,**,**,**,**]`
439+
Match(pat, str)
440+
441+
str = strings.Replace(str, ",", "情", -1)
442+
pat = strings.Replace(pat, ",", "情", -1)
443+
Match(pat, str)
444+
}

0 commit comments

Comments
 (0)