Skip to content

internal/codegen: cache pattern matching compilations #2028

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion internal/pattern/match.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package pattern
import (
"fmt"
"regexp"
"sync"
)

// Match is a wrapper of *regexp.Regexp.
Expand All @@ -11,9 +12,36 @@ type Match struct {
*regexp.Regexp
}

var (
matchCache = make(map[string]*Match)
matchCacheLock sync.RWMutex
)

// Compile takes our match expression as a string, and compiles it into a *Match object.
// Will return an error on an invalid pattern.
func MatchCompile(pattern string) (match *Match, err error) {
func MatchCompile(pattern string) (*Match, error) {
// check for pattern in cache
matchCacheLock.RLock()
matcher, ok := matchCache[pattern]
matchCacheLock.RUnlock()
if ok {
return matcher, nil
}

// pattern isn't in cache, compile it
matcher, err := matchCompile(pattern)
if err != nil {
return nil, err
}
// add it to the cache
matchCacheLock.Lock()
matchCache[pattern] = matcher
matchCacheLock.Unlock()

return matcher, nil
}

func matchCompile(pattern string) (match *Match, err error) {
regex := ""
escaped := false
arr := []byte(pattern)
Expand Down