github.com/gogf/gf@v1.16.9/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  
    14  var (
    15  	regexMu = sync.RWMutex{}
    16  	// Cache for regex object.
    17  	// Note that:
    18  	// 1. It uses sync.RWMutex ensuring the concurrent safety.
    19  	// 2. There's no expiring logic for this map.
    20  	regexMap = make(map[string]*regexp.Regexp)
    21  )
    22  
    23  // getRegexp returns *regexp.Regexp object with given <pattern>.
    24  // It uses cache to enhance the performance for compiling regular expression pattern,
    25  // which means, it will return the same *regexp.Regexp object with the same regular
    26  // expression pattern.
    27  //
    28  // It is concurrent-safe for multiple goroutines.
    29  func getRegexp(pattern string) (regex *regexp.Regexp, err error) {
    30  	// Retrieve the regular expression object using reading lock.
    31  	regexMu.RLock()
    32  	regex = regexMap[pattern]
    33  	regexMu.RUnlock()
    34  	if regex != nil {
    35  		return
    36  	}
    37  	// If it does not exist in the cache,
    38  	// it compiles the pattern and creates one.
    39  	regex, err = regexp.Compile(pattern)
    40  	if err != nil {
    41  		return
    42  	}
    43  	// Cache the result object using writing lock.
    44  	regexMu.Lock()
    45  	regexMap[pattern] = regex
    46  	regexMu.Unlock()
    47  	return
    48  }