gregex_cache.go 1.3 KB

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