and.go 673 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package matcher
  2. import (
  3. "fmt"
  4. )
  5. // And is a set of filters that should be evaluated as a logical
  6. // AND.
  7. type And[T any] struct {
  8. Matchers []Matcher[T]
  9. }
  10. func (a *And[T]) Add(m Matcher[T]) {
  11. a.Matchers = append(a.Matchers, m)
  12. }
  13. func (a *And[T]) String() string {
  14. s := "(and"
  15. for _, f := range a.Matchers {
  16. s += fmt.Sprintf(" %s", f)
  17. }
  18. s += ")"
  19. return s
  20. }
  21. // Matches is the canonical in-Go function for determining if T
  22. // matches a AND match rules.
  23. func (a *And[T]) Matches(that T) bool {
  24. filters := a.Matchers
  25. if len(filters) == 0 {
  26. return true
  27. }
  28. for _, filter := range filters {
  29. if !filter.Matches(that) {
  30. return false
  31. }
  32. }
  33. return true
  34. }