rule.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package geosite
  2. import "github.com/sagernet/sing-box/option"
  3. type ItemType = uint8
  4. const (
  5. RuleTypeDomain ItemType = iota
  6. RuleTypeDomainSuffix
  7. RuleTypeDomainKeyword
  8. RuleTypeDomainRegex
  9. )
  10. type Item struct {
  11. Type ItemType
  12. Value string
  13. }
  14. func Compile(code []Item) option.DefaultRule {
  15. var domainLength int
  16. var domainSuffixLength int
  17. var domainKeywordLength int
  18. var domainRegexLength int
  19. for _, item := range code {
  20. switch item.Type {
  21. case RuleTypeDomain:
  22. domainLength++
  23. case RuleTypeDomainSuffix:
  24. domainSuffixLength++
  25. case RuleTypeDomainKeyword:
  26. domainKeywordLength++
  27. case RuleTypeDomainRegex:
  28. domainRegexLength++
  29. }
  30. }
  31. var codeRule option.DefaultRule
  32. if domainLength > 0 {
  33. codeRule.Domain = make([]string, 0, domainLength)
  34. }
  35. if domainSuffixLength > 0 {
  36. codeRule.DomainSuffix = make([]string, 0, domainSuffixLength)
  37. }
  38. if domainKeywordLength > 0 {
  39. codeRule.DomainKeyword = make([]string, 0, domainKeywordLength)
  40. }
  41. if domainRegexLength > 0 {
  42. codeRule.DomainRegex = make([]string, 0, domainRegexLength)
  43. }
  44. for _, item := range code {
  45. switch item.Type {
  46. case RuleTypeDomain:
  47. codeRule.Domain = append(codeRule.Domain, item.Value)
  48. case RuleTypeDomainSuffix:
  49. codeRule.DomainSuffix = append(codeRule.DomainSuffix, item.Value)
  50. case RuleTypeDomainKeyword:
  51. codeRule.DomainKeyword = append(codeRule.DomainKeyword, item.Value)
  52. case RuleTypeDomainRegex:
  53. codeRule.DomainRegex = append(codeRule.DomainRegex, item.Value)
  54. }
  55. }
  56. return codeRule
  57. }