any_of.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package match
  2. import (
  3. "fmt"
  4. )
  5. type AnyOf struct {
  6. Matchers Matchers
  7. }
  8. func NewAnyOf(m ...Matcher) AnyOf {
  9. return AnyOf{Matchers(m)}
  10. }
  11. func (self *AnyOf) Add(m Matcher) error {
  12. self.Matchers = append(self.Matchers, m)
  13. return nil
  14. }
  15. func (self AnyOf) Match(s string) bool {
  16. for _, m := range self.Matchers {
  17. if m.Match(s) {
  18. return true
  19. }
  20. }
  21. return false
  22. }
  23. func (self AnyOf) Index(s string) (int, []int) {
  24. index := -1
  25. segments := acquireSegments(len(s))
  26. for _, m := range self.Matchers {
  27. idx, seg := m.Index(s)
  28. if idx == -1 {
  29. continue
  30. }
  31. if index == -1 || idx < index {
  32. index = idx
  33. segments = append(segments[:0], seg...)
  34. continue
  35. }
  36. if idx > index {
  37. continue
  38. }
  39. // here idx == index
  40. segments = appendMerge(segments, seg)
  41. }
  42. if index == -1 {
  43. releaseSegments(segments)
  44. return -1, nil
  45. }
  46. return index, segments
  47. }
  48. func (self AnyOf) Len() (l int) {
  49. l = -1
  50. for _, m := range self.Matchers {
  51. ml := m.Len()
  52. switch {
  53. case l == -1:
  54. l = ml
  55. continue
  56. case ml == -1:
  57. return -1
  58. case l != ml:
  59. return -1
  60. }
  61. }
  62. return
  63. }
  64. func (self AnyOf) String() string {
  65. return fmt.Sprintf("<any_of:[%s]>", self.Matchers)
  66. }