matchergroup_substr.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package strmatcher
  2. import (
  3. "sort"
  4. "strings"
  5. )
  6. // SubstrMatcherGroup is implementation of MatcherGroup,
  7. // It is simply implmeneted to comply with the priority specification of Substr matchers.
  8. type SubstrMatcherGroup struct {
  9. patterns []string
  10. values []uint32
  11. }
  12. // AddSubstrMatcher implements MatcherGroupForSubstr.AddSubstrMatcher.
  13. func (g *SubstrMatcherGroup) AddSubstrMatcher(matcher SubstrMatcher, value uint32) {
  14. g.patterns = append(g.patterns, matcher.Pattern())
  15. g.values = append(g.values, value)
  16. }
  17. // Match implements MatcherGroup.Match.
  18. func (g *SubstrMatcherGroup) Match(input string) []uint32 {
  19. result := []uint32{}
  20. for i, pattern := range g.patterns {
  21. for j := strings.LastIndex(input, pattern); j != -1; j = strings.LastIndex(input[:j], pattern) {
  22. result = append(result, uint32(j)<<16|uint32(i)&0xffff) // uint32: position (higher 16 bit) | patternIdx (lower 16 bit)
  23. }
  24. }
  25. // Sort the match results in dictionary order, so that:
  26. // 1. Pattern matched at smaller position (meaning matched further) takes precedence.
  27. // 2. When patterns matched at same position, pattern with smaller index (meaning inserted early) takes precedence.
  28. sort.Slice(result, func(i, j int) bool { return result[i] < result[j] })
  29. for i, entry := range result {
  30. result[i] = g.values[entry&0xffff] // Get pattern value from its index (the lower 16 bit)
  31. }
  32. return result
  33. }
  34. // MatchAny implements MatcherGroup.MatchAny.
  35. func (g *SubstrMatcherGroup) MatchAny(input string) bool {
  36. for _, pattern := range g.patterns {
  37. if strings.Contains(input, pattern) {
  38. return true
  39. }
  40. }
  41. return false
  42. }