strmatcher.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package strmatcher
  2. import (
  3. "regexp"
  4. )
  5. // Matcher is the interface to determine a string matches a pattern.
  6. type Matcher interface {
  7. // Match returns true if the given string matches a predefined pattern.
  8. Match(string) bool
  9. String() string
  10. }
  11. // Type is the type of the matcher.
  12. type Type byte
  13. const (
  14. // Full is the type of matcher that the input string must exactly equal to the pattern.
  15. Full Type = iota
  16. // Substr is the type of matcher that the input string must contain the pattern as a sub-string.
  17. Substr
  18. // Domain is the type of matcher that the input string must be a sub-domain or itself of the pattern.
  19. Domain
  20. // Regex is the type of matcher that the input string must matches the regular-expression pattern.
  21. Regex
  22. )
  23. // New creates a new Matcher based on the given pattern.
  24. func (t Type) New(pattern string) (Matcher, error) {
  25. // 1. regex matching is case-sensitive
  26. switch t {
  27. case Full:
  28. return fullMatcher(pattern), nil
  29. case Substr:
  30. return substrMatcher(pattern), nil
  31. case Domain:
  32. return domainMatcher(pattern), nil
  33. case Regex:
  34. r, err := regexp.Compile(pattern)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return &regexMatcher{
  39. pattern: r,
  40. }, nil
  41. default:
  42. panic("Unknown type")
  43. }
  44. }
  45. // IndexMatcher is the interface for matching with a group of matchers.
  46. type IndexMatcher interface {
  47. // Match returns the index of a matcher that matches the input. It returns empty array if no such matcher exists.
  48. Match(input string) []uint32
  49. }
  50. type matcherEntry struct {
  51. m Matcher
  52. id uint32
  53. }