-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathlive_pattern_state.go
More file actions
86 lines (78 loc) · 2.11 KB
/
Copy pathlive_pattern_state.go
File metadata and controls
86 lines (78 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package quamina
import (
"sync"
)
// LivePatternsState represents the required capabilities for maintaining the
// set of live patterns.
type LivePatternsState interface {
// Add adds a new pattern or updates an old pattern.
//
// Note that multiple patterns can be associated with the same X.
Add(x X, pattern string, buildMode MatcherBuildMode) error
// Delete removes all patterns associated with the given X and returns the
// number of removed patterns.
Delete(x X) (int, error)
// Iterate calls the given function for every stored pattern.
Iterate(func(x X, pattern string, buildMode MatcherBuildMode) error) error
// Contains returns true if x is in the live set; false otherwise.
Contains(x X) (bool, error)
}
// memState is a LivePatternsState that is just a slice of buildMode/pattern pairs
//
// Since the LivePatternsState implementation can be provided to the
// application, we're keeping things simple here initially.
type memStateEntry struct {
x X
pattern string
builderMode MatcherBuildMode
}
type memState struct {
lock sync.RWMutex
entries []memStateEntry
}
func newMemState() *memState {
return &memState{}
}
func (s *memState) Add(x X, pattern string, buildMode MatcherBuildMode) error {
s.lock.Lock()
defer s.lock.Unlock()
s.entries = append(s.entries, memStateEntry{x, pattern, buildMode})
return nil
}
func (s *memState) Delete(x X) (int, error) {
s.lock.Lock()
defer s.lock.Unlock()
howMany := 0
var newEntries []memStateEntry
for _, entry := range s.entries {
if entry.x == x {
howMany++
} else {
newEntries = append(newEntries, entry)
}
}
s.entries = newEntries
return howMany, nil
}
func (s *memState) Contains(x X) (bool, error) {
s.lock.Lock()
defer s.lock.Unlock()
for _, entry := range s.entries {
if entry.x == x {
return true, nil
}
}
return false, nil
}
func (s *memState) Iterate(f func(x X, pattern string, buildMode MatcherBuildMode) error) error {
s.lock.Lock()
defer s.lock.Unlock()
var err error
for _, entry := range s.entries {
err = f(entry.x, entry.pattern, entry.builderMode)
if err != nil {
break
}
}
return err
}