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.
v2ray-core/common/strmatcher/strmatcher.go

107 lines
2.6 KiB

7 years ago
package strmatcher
import (
"regexp"
)
7 years ago
// Matcher is the interface to determine a string matches a pattern.
7 years ago
type Matcher interface {
// Match returns true if the given string matches a predefined pattern.
7 years ago
Match(string) bool
String() string
7 years ago
}
// Type is the type of the matcher.
7 years ago
type Type byte
const (
// Full is the type of matcher that the input string must exactly equal to the pattern.
7 years ago
Full Type = iota
// Substr is the type of matcher that the input string must contain the pattern as a sub-string.
7 years ago
Substr
// Domain is the type of matcher that the input string must be a sub-domain or itself of the pattern.
7 years ago
Domain
// Regex is the type of matcher that the input string must matches the regular-expression pattern.
7 years ago
Regex
)
// New creates a new Matcher based on the given pattern.
7 years ago
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 &regexMatcher{
pattern: r,
}, nil
default:
panic("Unknown type")
}
}
// IndexMatcher is the interface for matching with a group of matchers.
type IndexMatcher interface {
// Match returns the the index of a matcher that matches the input. It returns empty array if no such matcher exists.
Match(input string) []uint32
}
7 years ago
type matcherEntry struct {
m Matcher
id uint32
}
// MatcherGroup is an implementation of IndexMatcher.
// Empty initialization works.
7 years ago
type MatcherGroup struct {
count uint32
fullMatcher FullMatcherGroup
domainMatcher DomainMatcherGroup
7 years ago
otherMatchers []matcherEntry
}
// Add adds a new Matcher into the MatcherGroup, and returns its index. The index will never be 0.
7 years ago
func (g *MatcherGroup) Add(m Matcher) uint32 {
g.count++
c := g.count
7 years ago
switch tm := m.(type) {
case fullMatcher:
g.fullMatcher.addMatcher(tm, c)
case domainMatcher:
g.domainMatcher.addMatcher(tm, c)
default:
7 years ago
g.otherMatchers = append(g.otherMatchers, matcherEntry{
m: m,
id: c,
})
}
return c
}
// Match implements IndexMatcher.Match.
func (g *MatcherGroup) Match(pattern string) []uint32 {
result := []uint32{}
result = append(result, g.fullMatcher.Match(pattern)...)
result = append(result, g.domainMatcher.Match(pattern)...)
7 years ago
for _, e := range g.otherMatchers {
if e.m.Match(pattern) {
result = append(result, e.id)
7 years ago
}
}
return result
7 years ago
}
// Size returns the number of matchers in the MatcherGroup.
7 years ago
func (g *MatcherGroup) Size() uint32 {
return g.count
}