1 Star 0 Fork 0

micro-tools/wf

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gregex_cache.go 1.05 KB
一键复制 编辑 原始数据 按行查看 历史
xushenghao 提交于 2021-05-19 10:41 . init
package gregex
import (
"regexp"
"sync"
)
var (
regexMu = sync.RWMutex{}
// Cache for regex object.
// Note that:
// 1. It uses sync.RWMutex ensuring the concurrent safety.
// 2. There's no expiring logic for this map.
regexMap = make(map[string]*regexp.Regexp)
)
// getRegexp returns *regexp.Regexp object with given <pattern>.
// It uses cache to enhance the performance for compiling regular expression pattern,
// which means, it will return the same *regexp.Regexp object with the same regular
// expression pattern.
//
// It is concurrent-safe for multiple goroutines.
func getRegexp(pattern string) (regex *regexp.Regexp, err error) {
// Retrieve the regular expression object using reading lock.
regexMu.RLock()
regex = regexMap[pattern]
regexMu.RUnlock()
if regex != nil {
return
}
// If it does not exist in the cache,
// it compiles the pattern and creates one.
regex, err = regexp.Compile(pattern)
if err != nil {
return
}
// Cache the result object using writing lock.
regexMu.Lock()
regexMap[pattern] = regex
regexMu.Unlock()
return
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/micro-tools/wf.git
git@gitee.com:micro-tools/wf.git
micro-tools
wf
wf
v1.0.1

搜索帮助