github.com/database64128/shadowsocks-go@v1.10.2-0.20240315062903-143a773533f1/domainset/matcher_keyword.go (about)

     1  package domainset
     2  
     3  import "strings"
     4  
     5  // KeywordLinearMatcher matches keyword rules by iterating over the keywords.
     6  type KeywordLinearMatcher []string
     7  
     8  // NewKeywordLinearMatcher creates a [KeywordLinearMatcher] with the specified initial capacity.
     9  func NewKeywordLinearMatcher(capacity int) MatcherBuilder {
    10  	klm := make(KeywordLinearMatcher, 0, capacity)
    11  	return &klm
    12  }
    13  
    14  // Match implements the Matcher Match method.
    15  func (klm KeywordLinearMatcher) Match(domain string) bool {
    16  	for _, keyword := range klm {
    17  		if strings.Contains(domain, keyword) {
    18  			return true
    19  		}
    20  	}
    21  	return false
    22  }
    23  
    24  // Insert implements the MatcherBuilder Insert method.
    25  func (klmp *KeywordLinearMatcher) Insert(rule string) {
    26  	*klmp = append(*klmp, rule)
    27  }
    28  
    29  // Rules implements the MatcherBuilder Rules method.
    30  func (klm KeywordLinearMatcher) Rules() []string {
    31  	return klm
    32  }
    33  
    34  // MatcherCount implements the MatcherBuilder MatcherCount method.
    35  func (klm KeywordLinearMatcher) MatcherCount() int {
    36  	if len(klm) == 0 {
    37  		return 0
    38  	}
    39  	return 1
    40  }
    41  
    42  // AppendTo implements the MatcherBuilder AppendTo method.
    43  func (klm KeywordLinearMatcher) AppendTo(matchers []Matcher) ([]Matcher, error) {
    44  	if len(klm) == 0 {
    45  		return matchers, nil
    46  	}
    47  	return append(matchers, klm), nil
    48  }