-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrules_map.go
59 lines (52 loc) · 1.09 KB
/
rules_map.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package progszy
import (
"regexp"
"sync"
)
// TODO(js) This should probably have its own tests.
type rulesMap struct {
mu sync.RWMutex
regexpByPattern map[string]*regexp.Regexp
}
func newRulesMap() *rulesMap {
m := rulesMap{
regexpByPattern: make(map[string]*regexp.Regexp),
}
return &m
}
func (m *rulesMap) get(pat string) (*regexp.Regexp, error) {
m.mu.RLock()
re, ok := m.regexpByPattern[pat]
m.mu.RUnlock()
if ok {
return re, nil
}
return m.put(pat)
}
func (m *rulesMap) getAll(pats []string) ([]*regexp.Regexp, error) {
// TODO(js) Time stats for creation/compilation of regex rules.
relist := make([]*regexp.Regexp, len(pats))
for i, pat := range pats {
re, err := m.get(pat)
if err != nil {
return nil, err
}
relist[i] = re
}
return relist, nil
}
func (m *rulesMap) put(pat string) (*regexp.Regexp, error) {
m.mu.Lock()
defer m.mu.Unlock()
re, ok := m.regexpByPattern[pat]
if ok {
// Already exists, nothing to do.
return re, nil
}
re, err := regexp.Compile(pat)
if err != nil {
return nil, err
}
m.regexpByPattern[pat] = re
return re, nil
}