regex_cache.go 1.1 KB

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