github.com/netdata/go.d.plugin@v0.58.1/pkg/matcher/logical.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package matcher 4 5 type ( 6 trueMatcher struct{} 7 falseMatcher struct{} 8 andMatcher struct{ lhs, rhs Matcher } 9 orMatcher struct{ lhs, rhs Matcher } 10 negMatcher struct{ Matcher } 11 ) 12 13 var ( 14 matcherT trueMatcher 15 matcherF falseMatcher 16 ) 17 18 // TRUE returns a matcher which always returns true 19 func TRUE() Matcher { 20 return matcherT 21 } 22 23 // FALSE returns a matcher which always returns false 24 func FALSE() Matcher { 25 return matcherF 26 } 27 28 // Not returns a matcher which positive the sub-matcher's result 29 func Not(m Matcher) Matcher { 30 switch m { 31 case TRUE(): 32 return FALSE() 33 case FALSE(): 34 return TRUE() 35 default: 36 return negMatcher{m} 37 } 38 } 39 40 // And returns a matcher which returns true only if all of it's sub-matcher return true 41 func And(lhs, rhs Matcher, others ...Matcher) Matcher { 42 var matcher Matcher 43 switch lhs { 44 case TRUE(): 45 matcher = rhs 46 case FALSE(): 47 matcher = FALSE() 48 default: 49 switch rhs { 50 case TRUE(): 51 matcher = lhs 52 case FALSE(): 53 matcher = FALSE() 54 default: 55 matcher = andMatcher{lhs, rhs} 56 } 57 } 58 if len(others) > 0 { 59 return And(matcher, others[0], others[1:]...) 60 } 61 return matcher 62 } 63 64 // Or returns a matcher which returns true if any of it's sub-matcher return true 65 func Or(lhs, rhs Matcher, others ...Matcher) Matcher { 66 var matcher Matcher 67 switch lhs { 68 case TRUE(): 69 matcher = TRUE() 70 case FALSE(): 71 matcher = rhs 72 default: 73 switch rhs { 74 case TRUE(): 75 matcher = TRUE() 76 case FALSE(): 77 matcher = lhs 78 default: 79 matcher = orMatcher{lhs, rhs} 80 } 81 } 82 if len(others) > 0 { 83 return Or(matcher, others[0], others[1:]...) 84 } 85 return matcher 86 } 87 88 func (trueMatcher) Match(_ []byte) bool { return true } 89 func (trueMatcher) MatchString(_ string) bool { return true } 90 91 func (falseMatcher) Match(_ []byte) bool { return false } 92 func (falseMatcher) MatchString(_ string) bool { return false } 93 94 func (m andMatcher) Match(b []byte) bool { return m.lhs.Match(b) && m.rhs.Match(b) } 95 func (m andMatcher) MatchString(s string) bool { return m.lhs.MatchString(s) && m.rhs.MatchString(s) } 96 97 func (m orMatcher) Match(b []byte) bool { return m.lhs.Match(b) || m.rhs.Match(b) } 98 func (m orMatcher) MatchString(s string) bool { return m.lhs.MatchString(s) || m.rhs.MatchString(s) } 99 100 func (m negMatcher) Match(b []byte) bool { return !m.Matcher.Match(b) } 101 func (m negMatcher) MatchString(s string) bool { return !m.Matcher.MatchString(s) }