matchergroup_domain.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package strmatcher
  2. type trieNode struct {
  3. values []uint32
  4. children map[string]*trieNode
  5. }
  6. // DomainMatcherGroup is an implementation of MatcherGroup.
  7. // It uses trie to optimize both memory consumption and lookup speed. Trie node is domain label based.
  8. type DomainMatcherGroup struct {
  9. root *trieNode
  10. }
  11. func NewDomainMatcherGroup() *DomainMatcherGroup {
  12. return &DomainMatcherGroup{
  13. root: new(trieNode),
  14. }
  15. }
  16. // AddDomainMatcher implements MatcherGroupForDomain.AddDomainMatcher.
  17. func (g *DomainMatcherGroup) AddDomainMatcher(matcher DomainMatcher, value uint32) {
  18. node := g.root
  19. pattern := matcher.Pattern()
  20. for i := len(pattern); i > 0; {
  21. var part string
  22. for j := i - 1; ; j-- {
  23. if pattern[j] == '.' {
  24. part = pattern[j+1 : i]
  25. i = j
  26. break
  27. }
  28. if j == 0 {
  29. part = pattern[j:i]
  30. i = j
  31. break
  32. }
  33. }
  34. if node.children == nil {
  35. node.children = make(map[string]*trieNode)
  36. }
  37. next := node.children[part]
  38. if next == nil {
  39. next = new(trieNode)
  40. node.children[part] = next
  41. }
  42. node = next
  43. }
  44. node.values = append(node.values, value)
  45. }
  46. // Match implements MatcherGroup.Match.
  47. func (g *DomainMatcherGroup) Match(input string) []uint32 {
  48. matches := make([][]uint32, 0, 5)
  49. node := g.root
  50. for i := len(input); i > 0; {
  51. for j := i - 1; ; j-- {
  52. if input[j] == '.' { // Domain label found
  53. node = node.children[input[j+1:i]]
  54. i = j
  55. break
  56. }
  57. if j == 0 { // The last part of domain label
  58. node = node.children[input[j:i]]
  59. i = j
  60. break
  61. }
  62. }
  63. if node == nil { // No more match if no trie edge transition
  64. break
  65. }
  66. if len(node.values) > 0 { // Found matched matchers
  67. matches = append(matches, node.values)
  68. }
  69. if node.children == nil { // No more match if leaf node reached
  70. break
  71. }
  72. }
  73. return CompositeMatchesReverse(matches)
  74. }
  75. // MatchAny implements MatcherGroup.MatchAny.
  76. func (g *DomainMatcherGroup) MatchAny(input string) bool {
  77. node := g.root
  78. for i := len(input); i > 0; {
  79. for j := i - 1; ; j-- {
  80. if input[j] == '.' {
  81. node = node.children[input[j+1:i]]
  82. i = j
  83. break
  84. }
  85. if j == 0 {
  86. node = node.children[input[j:i]]
  87. i = j
  88. break
  89. }
  90. }
  91. if node == nil {
  92. return false
  93. }
  94. if len(node.values) > 0 {
  95. return true
  96. }
  97. if node.children == nil {
  98. return false
  99. }
  100. }
  101. return false
  102. }