indexmatcher_linear.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package strmatcher
  2. // LinearIndexMatcher is an implementation of IndexMatcher.
  3. type LinearIndexMatcher struct {
  4. count uint32
  5. full *FullMatcherGroup
  6. domain *DomainMatcherGroup
  7. substr *SubstrMatcherGroup
  8. regex *SimpleMatcherGroup
  9. }
  10. func NewLinearIndexMatcher() *LinearIndexMatcher {
  11. return new(LinearIndexMatcher)
  12. }
  13. // Add implements IndexMatcher.Add.
  14. func (g *LinearIndexMatcher) Add(matcher Matcher) uint32 {
  15. g.count++
  16. index := g.count
  17. switch matcher := matcher.(type) {
  18. case FullMatcher:
  19. if g.full == nil {
  20. g.full = NewFullMatcherGroup()
  21. }
  22. g.full.AddFullMatcher(matcher, index)
  23. case DomainMatcher:
  24. if g.domain == nil {
  25. g.domain = NewDomainMatcherGroup()
  26. }
  27. g.domain.AddDomainMatcher(matcher, index)
  28. case SubstrMatcher:
  29. if g.substr == nil {
  30. g.substr = new(SubstrMatcherGroup)
  31. }
  32. g.substr.AddSubstrMatcher(matcher, index)
  33. default:
  34. if g.regex == nil {
  35. g.regex = new(SimpleMatcherGroup)
  36. }
  37. g.regex.AddMatcher(matcher, index)
  38. }
  39. return index
  40. }
  41. // Build implements IndexMatcher.Build.
  42. func (*LinearIndexMatcher) Build() error {
  43. return nil
  44. }
  45. // Match implements IndexMatcher.Match.
  46. func (g *LinearIndexMatcher) Match(input string) []uint32 {
  47. // Allocate capacity to prevent matches escaping to heap
  48. result := make([][]uint32, 0, 5)
  49. if g.full != nil {
  50. if matches := g.full.Match(input); len(matches) > 0 {
  51. result = append(result, matches)
  52. }
  53. }
  54. if g.domain != nil {
  55. if matches := g.domain.Match(input); len(matches) > 0 {
  56. result = append(result, matches)
  57. }
  58. }
  59. if g.substr != nil {
  60. if matches := g.substr.Match(input); len(matches) > 0 {
  61. result = append(result, matches)
  62. }
  63. }
  64. if g.regex != nil {
  65. if matches := g.regex.Match(input); len(matches) > 0 {
  66. result = append(result, matches)
  67. }
  68. }
  69. return CompositeMatches(result)
  70. }
  71. // MatchAny implements IndexMatcher.MatchAny.
  72. func (g *LinearIndexMatcher) MatchAny(input string) bool {
  73. if g.full != nil && g.full.MatchAny(input) {
  74. return true
  75. }
  76. if g.domain != nil && g.domain.MatchAny(input) {
  77. return true
  78. }
  79. if g.substr != nil && g.substr.MatchAny(input) {
  80. return true
  81. }
  82. return g.regex != nil && g.regex.MatchAny(input)
  83. }
  84. // Size implements IndexMatcher.Size.
  85. func (g *LinearIndexMatcher) Size() uint32 {
  86. return g.count
  87. }