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

     1  package domainset
     2  
     3  import (
     4  	"regexp"
     5  
     6  	"github.com/database64128/shadowsocks-go/slicehelper"
     7  )
     8  
     9  // RegexpMatcher adapts [regexp.Regexp] to the [Matcher] interface.
    10  type RegexpMatcher regexp.Regexp
    11  
    12  // Match implements the Matcher Match method.
    13  func (rlmp *RegexpMatcher) Match(domain string) bool {
    14  	return (*regexp.Regexp)(rlmp).MatchString(domain)
    15  }
    16  
    17  // RegexpMatcherBuilder stores regular expressions for building [RegexpMatcher] instances.
    18  type RegexpMatcherBuilder []string
    19  
    20  // NewRegexpMatcherBuilder creates a new [RegexpMatcherBuilder] with the specified initial capacity.
    21  func NewRegexpMatcherBuilder(capacity int) MatcherBuilder {
    22  	rmb := make(RegexpMatcherBuilder, 0, capacity)
    23  	return &rmb
    24  }
    25  
    26  // Insert implements the MatcherBuilder Insert method.
    27  func (rmbp *RegexpMatcherBuilder) Insert(rule string) {
    28  	*rmbp = append(*rmbp, rule)
    29  }
    30  
    31  // Rules implements the MatcherBuilder Rules method.
    32  func (rmb RegexpMatcherBuilder) Rules() []string {
    33  	return rmb
    34  }
    35  
    36  // MatcherCount implements the MatcherBuilder MatcherCount method.
    37  func (rmb RegexpMatcherBuilder) MatcherCount() int {
    38  	return len(rmb)
    39  }
    40  
    41  // AppendTo implements the MatcherBuilder AppendTo method.
    42  func (rmb RegexpMatcherBuilder) AppendTo(matchers []Matcher) ([]Matcher, error) {
    43  	if len(rmb) == 0 {
    44  		return matchers, nil
    45  	}
    46  
    47  	head, tail := slicehelper.Extend(matchers, len(rmb))
    48  
    49  	for i, r := range rmb {
    50  		re, err := regexp.Compile(r)
    51  		if err != nil {
    52  			return matchers, err
    53  		}
    54  		tail[i] = (*RegexpMatcher)(re)
    55  	}
    56  
    57  	return head, nil
    58  }