github.com/metacubex/mihomo@v1.18.5/component/geodata/strmatcher/strmatcher.go (about)

     1  package strmatcher
     2  
     3  import (
     4  	"regexp"
     5  )
     6  
     7  // Matcher is the interface to determine a string matches a pattern.
     8  type Matcher interface {
     9  	// Match returns true if the given string matches a predefined pattern.
    10  	Match(string) bool
    11  	String() string
    12  }
    13  
    14  // Type is the type of the matcher.
    15  type Type byte
    16  
    17  const (
    18  	// Full is the type of matcher that the input string must exactly equal to the pattern.
    19  	Full Type = iota
    20  	// Substr is the type of matcher that the input string must contain the pattern as a sub-string.
    21  	Substr
    22  	// Domain is the type of matcher that the input string must be a sub-domain or itself of the pattern.
    23  	Domain
    24  	// Regex is the type of matcher that the input string must matches the regular-expression pattern.
    25  	Regex
    26  )
    27  
    28  // New creates a new Matcher based on the given pattern.
    29  func (t Type) New(pattern string) (Matcher, error) {
    30  	// 1. regex matching is case-sensitive
    31  	switch t {
    32  	case Full:
    33  		return fullMatcher(pattern), nil
    34  	case Substr:
    35  		return substrMatcher(pattern), nil
    36  	case Domain:
    37  		return domainMatcher(pattern), nil
    38  	case Regex:
    39  		r, err := regexp.Compile(pattern)
    40  		if err != nil {
    41  			return nil, err
    42  		}
    43  		return &regexMatcher{
    44  			pattern: r,
    45  		}, nil
    46  	default:
    47  		panic("Unknown type")
    48  	}
    49  }
    50  
    51  // IndexMatcher is the interface for matching with a group of matchers.
    52  type IndexMatcher interface {
    53  	// Match returns the index of a matcher that matches the input. It returns empty array if no such matcher exists.
    54  	Match(input string) []uint32
    55  }
    56  
    57  type matcherEntry struct {
    58  	m  Matcher
    59  	id uint32
    60  }