domain_matcher.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package strmatcher
  2. import "strings"
  3. func breakDomain(domain string) []string {
  4. return strings.Split(domain, ".")
  5. }
  6. type node struct {
  7. value uint32
  8. sub map[string]*node
  9. }
  10. // DomainMatcherGroup is a IndexMatcher for a large set of Domain matchers.
  11. // Visible for testing only.
  12. type DomainMatcherGroup struct {
  13. root *node
  14. }
  15. func (g *DomainMatcherGroup) Add(domain string, value uint32) {
  16. if g.root == nil {
  17. g.root = new(node)
  18. }
  19. current := g.root
  20. parts := breakDomain(domain)
  21. for i := len(parts) - 1; i >= 0; i-- {
  22. if current.value > 0 {
  23. // if current node is already a match, it is not necessary to match further.
  24. return
  25. }
  26. part := parts[i]
  27. if current.sub == nil {
  28. current.sub = make(map[string]*node)
  29. }
  30. next := current.sub[part]
  31. if next == nil {
  32. next = new(node)
  33. current.sub[part] = next
  34. }
  35. current = next
  36. }
  37. current.value = value
  38. current.sub = nil // shortcut sub nodes as current node is a match.
  39. }
  40. func (g *DomainMatcherGroup) addMatcher(m domainMatcher, value uint32) {
  41. g.Add(string(m), value)
  42. }
  43. func (g *DomainMatcherGroup) Match(domain string) uint32 {
  44. current := g.root
  45. if current == nil {
  46. return 0
  47. }
  48. parts := breakDomain(domain)
  49. for i := len(parts) - 1; i >= 0; i-- {
  50. part := parts[i]
  51. if current.sub == nil {
  52. break
  53. }
  54. next := current.sub[part]
  55. if next == nil {
  56. break
  57. }
  58. current = next
  59. }
  60. return current.value
  61. }