gregex_cache.go 1.4 KB

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