summaryrefslogtreecommitdiffstats
path: root/tpl
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2023-07-27 19:20:48 +0200
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2023-07-27 19:23:12 +0200
commit4d7af757c99a561744c87c477d10b89e5c9d7e35 (patch)
treed37b0d3fb9d5e6836737364a75c3dc53acff5559 /tpl
parent7f058b8bab947db98939ed27a7c2a08468323d08 (diff)
Add a common regexp cache
``` BenchmarkGetOrCompileRegexp-10 73959368 13.71 ns/op 0 B/op 0 allocs/op BenchmarkCompileRegexp-10 3143529 380.1 ns/op 872 B/op 10 allocs/op ```
Diffstat (limited to 'tpl')
-rw-r--r--tpl/strings/regexp.go47
1 files changed, 4 insertions, 43 deletions
diff --git a/tpl/strings/regexp.go b/tpl/strings/regexp.go
index 8d53b23b3..df323c216 100644
--- a/tpl/strings/regexp.go
+++ b/tpl/strings/regexp.go
@@ -14,16 +14,14 @@
package strings
import (
- "regexp"
- "sync"
-
+ "github.com/gohugoio/hugo/common/hstrings"
"github.com/spf13/cast"
)
// FindRE returns a list of strings that match the regular expression. By default all matches
// will be included. The number of matches can be limited with an optional third parameter.
func (ns *Namespace) FindRE(expr string, content any, limit ...any) ([]string, error) {
- re, err := reCache.Get(expr)
+ re, err := hstrings.GetOrCompileRegexp(expr)
if err != nil {
return nil, err
}
@@ -54,7 +52,7 @@ func (ns *Namespace) FindRE(expr string, content any, limit ...any) ([]string, e
// limited with the optional limit parameter. A return value of nil indicates
// no match.
func (ns *Namespace) FindRESubmatch(expr string, content any, limit ...any) ([][]string, error) {
- re, err := reCache.Get(expr)
+ re, err := hstrings.GetOrCompileRegexp(expr)
if err != nil {
return nil, err
}
@@ -102,7 +100,7 @@ func (ns *Namespace) ReplaceRE(pattern, repl, s any, n ...any) (_ string, err er
}
}
- re, err := reCache.Get(sp)
+ re, err := hstrings.GetOrCompileRegexp(sp)
if err != nil {
return "", err
}
@@ -116,40 +114,3 @@ func (ns *Namespace) ReplaceRE(pattern, repl, s any, n ...any) (_ string, err er
return re.ReplaceAllString(str, sr)
}), nil
}
-
-// regexpCache represents a cache of regexp objects protected by a mutex.
-type regexpCache struct {
- mu sync.RWMutex
- re map[string]*regexp.Regexp
-}
-
-// Get retrieves a regexp object from the cache based upon the pattern.
-// If the pattern is not found in the cache, create one
-func (rc *regexpCache) Get(pattern string) (re *regexp.Regexp, err error) {
- var ok bool
-
- if re, ok = rc.get(pattern); !ok {
- re, err = regexp.Compile(pattern)
- if err != nil {
- return nil, err
- }
- rc.set(pattern, re)
- }
-
- return re, nil
-}
-
-func (rc *regexpCache) get(key string) (re *regexp.Regexp, ok bool) {
- rc.mu.RLock()
- re, ok = rc.re[key]
- rc.mu.RUnlock()
- return
-}
-
-func (rc *regexpCache) set(key string, re *regexp.Regexp) {
- rc.mu.Lock()
- rc.re[key] = re
- rc.mu.Unlock()
-}
-
-var reCache = regexpCache{re: make(map[string]*regexp.Regexp)}