github.com/zhongdalu/gf@v1.0.0/g/text/gregex/gregex_cache.go (about)

     1  // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/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  	// TODO There's no expiring logic for this map.
    18  	regexMap = make(map[string]*regexp.Regexp)
    19  )
    20  
    21  // getRegexp returns *regexp.Regexp object with given <pattern>.
    22  // It uses cache to enhance the performance for compiling regular expression pattern,
    23  // which means, it will return the same *regexp.Regexp object with the same regular
    24  // expression pattern.
    25  func getRegexp(pattern string) (*regexp.Regexp, error) {
    26  	if r := getCache(pattern); r != nil {
    27  		return r, nil
    28  	}
    29  	if r, err := regexp.Compile(pattern); err == nil {
    30  		setCache(pattern, r)
    31  		return r, nil
    32  	} else {
    33  		return nil, err
    34  	}
    35  }
    36  
    37  // getCache returns *regexp.Regexp object from cache by given <pattern>, for internal usage.
    38  func getCache(pattern string) (regex *regexp.Regexp) {
    39  	regexMu.RLock()
    40  	regex = regexMap[pattern]
    41  	regexMu.RUnlock()
    42  	return
    43  }
    44  
    45  // setCache stores *regexp.Regexp object into cache, for internal usage.
    46  func setCache(pattern string, regex *regexp.Regexp) {
    47  	regexMu.Lock()
    48  	regexMap[pattern] = regex
    49  	regexMu.Unlock()
    50  }