github.com/gogf/gf/v2@v2.7.4/text/gregex/gregex_cache.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gregex
     8  
     9  import (
    10  	"regexp"
    11  	"sync"
    12  
    13  	"github.com/gogf/gf/v2/errors/gerror"
    14  )
    15  
    16  var (
    17  	regexMu = sync.RWMutex{}
    18  
    19  	// Cache for regex object.
    20  	// Note that:
    21  	// 1. It uses sync.RWMutex ensuring the concurrent safety.
    22  	// 2. There's no expiring logic for this map.
    23  	regexMap = make(map[string]*regexp.Regexp)
    24  )
    25  
    26  // getRegexp returns *regexp.Regexp object with given `pattern`.
    27  // It uses cache to enhance the performance for compiling regular expression pattern,
    28  // which means, it will return the same *regexp.Regexp object with the same regular
    29  // expression pattern.
    30  //
    31  // It is concurrent-safe for multiple goroutines.
    32  func getRegexp(pattern string) (regex *regexp.Regexp, err error) {
    33  	// Retrieve the regular expression object using reading lock.
    34  	regexMu.RLock()
    35  	regex = regexMap[pattern]
    36  	regexMu.RUnlock()
    37  	if regex != nil {
    38  		return
    39  	}
    40  	// If it does not exist in the cache,
    41  	// it compiles the pattern and creates one.
    42  	if regex, err = regexp.Compile(pattern); err != nil {
    43  		err = gerror.Wrapf(err, `regexp.Compile failed for pattern "%s"`, pattern)
    44  		return
    45  	}
    46  	// Cache the result object using writing lock.
    47  	regexMu.Lock()
    48  	regexMap[pattern] = regex
    49  	regexMu.Unlock()
    50  	return
    51  }