You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rexp.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validate
  15. import (
  16. re "regexp"
  17. "sync"
  18. "sync/atomic"
  19. )
  20. // Cache for compiled regular expressions
  21. var (
  22. cacheMutex = &sync.Mutex{}
  23. reDict = atomic.Value{} //map[string]*re.Regexp
  24. )
  25. func compileRegexp(pattern string) (*re.Regexp, error) {
  26. if cache, ok := reDict.Load().(map[string]*re.Regexp); ok {
  27. if r := cache[pattern]; r != nil {
  28. return r, nil
  29. }
  30. }
  31. r, err := re.Compile(pattern)
  32. if err != nil {
  33. return nil, err
  34. }
  35. cacheRegexp(r)
  36. return r, nil
  37. }
  38. func mustCompileRegexp(pattern string) *re.Regexp {
  39. if cache, ok := reDict.Load().(map[string]*re.Regexp); ok {
  40. if r := cache[pattern]; r != nil {
  41. return r
  42. }
  43. }
  44. r := re.MustCompile(pattern)
  45. cacheRegexp(r)
  46. return r
  47. }
  48. func cacheRegexp(r *re.Regexp) {
  49. cacheMutex.Lock()
  50. defer cacheMutex.Unlock()
  51. if cache, ok := reDict.Load().(map[string]*re.Regexp); !ok || cache[r.String()] == nil {
  52. newCache := map[string]*re.Regexp{
  53. r.String(): r,
  54. }
  55. for k, v := range cache {
  56. newCache[k] = v
  57. }
  58. reDict.Store(newCache)
  59. }
  60. }