gf/text/gregex/gregex_cache.go

49 lines
1.3 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2019-01-31 13:00:17 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2019-01-31 13:00:17 +08:00
package gregex
import (
2019-06-19 09:06:52 +08:00
"regexp"
"sync"
2019-01-31 13:00:17 +08:00
)
var (
2019-06-19 09:06:52 +08:00
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.
2019-06-19 09:06:52 +08:00
regexMap = make(map[string]*regexp.Regexp)
2019-01-31 13:00:17 +08:00
)
// 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.
2019-06-19 09:06:52 +08:00
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.
2019-06-19 09:06:52 +08:00
regexMu.Lock()
regexMap[pattern] = regex
regexMu.Unlock()
return
2019-01-31 13:00:17 +08:00
}