podman
71 строка · 1.6 Кб
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
15package validate
16
17import (
18re "regexp"
19"sync"
20"sync/atomic"
21)
22
23// Cache for compiled regular expressions
24var (
25cacheMutex = &sync.Mutex{}
26reDict = atomic.Value{} // map[string]*re.Regexp
27)
28
29func compileRegexp(pattern string) (*re.Regexp, error) {
30if cache, ok := reDict.Load().(map[string]*re.Regexp); ok {
31if r := cache[pattern]; r != nil {
32return r, nil
33}
34}
35
36r, err := re.Compile(pattern)
37if err != nil {
38return nil, err
39}
40cacheRegexp(r)
41return r, nil
42}
43
44func mustCompileRegexp(pattern string) *re.Regexp {
45if cache, ok := reDict.Load().(map[string]*re.Regexp); ok {
46if r := cache[pattern]; r != nil {
47return r
48}
49}
50
51r := re.MustCompile(pattern)
52cacheRegexp(r)
53return r
54}
55
56func cacheRegexp(r *re.Regexp) {
57cacheMutex.Lock()
58defer cacheMutex.Unlock()
59
60if cache, ok := reDict.Load().(map[string]*re.Regexp); !ok || cache[r.String()] == nil {
61newCache := map[string]*re.Regexp{
62r.String(): r,
63}
64
65for k, v := range cache {
66newCache[k] = v
67}
68
69reDict.Store(newCache)
70}
71}
72