forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strmatcher.go
89 lines (74 loc) · 1.33 KB
/
strmatcher.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package strmatcher
import "regexp"
type Matcher interface {
Match(string) bool
}
type Type byte
const (
Full Type = iota
Substr
Domain
Regex
)
func (t Type) New(pattern string) (Matcher, error) {
switch t {
case Full:
return fullMatcher(pattern), nil
case Substr:
return substrMatcher(pattern), nil
case Domain:
return domainMatcher(pattern), nil
case Regex:
r, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return ®exMatcher{
pattern: r,
}, nil
default:
panic("Unknown type")
}
}
type matcherEntry struct {
m Matcher
id uint32
}
type MatcherGroup struct {
count uint32
fullMatchers map[string]uint32
otherMatchers []matcherEntry
}
func NewMatcherGroup() *MatcherGroup {
return &MatcherGroup{
count: 1,
fullMatchers: make(map[string]uint32),
}
}
func (g *MatcherGroup) Add(m Matcher) uint32 {
c := g.count
g.count++
if fm, ok := m.(fullMatcher); ok {
g.fullMatchers[string(fm)] = c
} else {
g.otherMatchers = append(g.otherMatchers, matcherEntry{
m: m,
id: c,
})
}
return c
}
func (g *MatcherGroup) Match(pattern string) uint32 {
if c, f := g.fullMatchers[pattern]; f {
return c
}
for _, e := range g.otherMatchers {
if e.m.Match(pattern) {
return e.id
}
}
return 0
}
func (g *MatcherGroup) Size() uint32 {
return g.count
}