Skip to content

Commit f1eef01

Browse files
internal/codegen: cache pattern matching compilations (#2028)
1 parent d64a68b commit f1eef01

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

internal/pattern/match.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package pattern
33
import (
44
"fmt"
55
"regexp"
6+
"sync"
67
)
78

89
// Match is a wrapper of *regexp.Regexp.
@@ -11,9 +12,36 @@ type Match struct {
1112
*regexp.Regexp
1213
}
1314

15+
var (
16+
matchCache = make(map[string]*Match)
17+
matchCacheLock sync.RWMutex
18+
)
19+
1420
// Compile takes our match expression as a string, and compiles it into a *Match object.
1521
// Will return an error on an invalid pattern.
16-
func MatchCompile(pattern string) (match *Match, err error) {
22+
func MatchCompile(pattern string) (*Match, error) {
23+
// check for pattern in cache
24+
matchCacheLock.RLock()
25+
matcher, ok := matchCache[pattern]
26+
matchCacheLock.RUnlock()
27+
if ok {
28+
return matcher, nil
29+
}
30+
31+
// pattern isn't in cache, compile it
32+
matcher, err := matchCompile(pattern)
33+
if err != nil {
34+
return nil, err
35+
}
36+
// add it to the cache
37+
matchCacheLock.Lock()
38+
matchCache[pattern] = matcher
39+
matchCacheLock.Unlock()
40+
41+
return matcher, nil
42+
}
43+
44+
func matchCompile(pattern string) (match *Match, err error) {
1745
regex := ""
1846
escaped := false
1947
arr := []byte(pattern)

0 commit comments

Comments
 (0)