github.com/netdata/go.d.plugin@v0.58.1/pkg/matcher/cache.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package matcher 4 5 import "sync" 6 7 type ( 8 cachedMatcher struct { 9 matcher Matcher 10 11 mux sync.RWMutex 12 cache map[string]bool 13 } 14 ) 15 16 // WithCache adds cache to the matcher. 17 func WithCache(m Matcher) Matcher { 18 switch m { 19 case TRUE(), FALSE(): 20 return m 21 default: 22 return &cachedMatcher{matcher: m, cache: make(map[string]bool)} 23 } 24 } 25 26 func (m *cachedMatcher) Match(b []byte) bool { 27 s := string(b) 28 if result, ok := m.fetch(s); ok { 29 return result 30 } 31 result := m.matcher.Match(b) 32 m.put(s, result) 33 return result 34 } 35 36 func (m *cachedMatcher) MatchString(s string) bool { 37 if result, ok := m.fetch(s); ok { 38 return result 39 } 40 result := m.matcher.MatchString(s) 41 m.put(s, result) 42 return result 43 } 44 45 func (m *cachedMatcher) fetch(key string) (result bool, ok bool) { 46 m.mux.RLock() 47 result, ok = m.cache[key] 48 m.mux.RUnlock() 49 return 50 } 51 52 func (m *cachedMatcher) put(key string, result bool) { 53 m.mux.Lock() 54 m.cache[key] = result 55 m.mux.Unlock() 56 }