File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ package pattern
3
3
import (
4
4
"fmt"
5
5
"regexp"
6
+ "sync"
6
7
)
7
8
8
9
// Match is a wrapper of *regexp.Regexp.
@@ -11,9 +12,36 @@ type Match struct {
11
12
* regexp.Regexp
12
13
}
13
14
15
+ var (
16
+ matchCache = make (map [string ]* Match )
17
+ matchCacheLock sync.RWMutex
18
+ )
19
+
14
20
// Compile takes our match expression as a string, and compiles it into a *Match object.
15
21
// 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 ) {
17
45
regex := ""
18
46
escaped := false
19
47
arr := []byte (pattern )
You can’t perform that action at this time.
0 commit comments