-
Notifications
You must be signed in to change notification settings - Fork 18
/
mem.go
63 lines (54 loc) · 1.17 KB
/
mem.go
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
package distconf
import "sync"
type memConfig struct {
vals map[string][]byte
watches map[string][]backingCallbackFunction
mu sync.Mutex
}
func (m *memConfig) Get(key string) ([]byte, error) {
m.mu.Lock()
defer m.mu.Unlock()
b, exists := m.vals[key]
if !exists {
return nil, nil
}
return b, nil
}
func (m *memConfig) Write(key string, value []byte) error {
m.mu.Lock()
if value == nil {
delete(m.vals, key)
} else {
m.vals[key] = value
}
m.mu.Unlock()
for _, calls := range m.watches[key] {
calls(key)
}
return nil
}
func (m *memConfig) Watch(key string, callback backingCallbackFunction) error {
m.mu.Lock()
defer m.mu.Unlock()
_, existing := m.watches[key]
if !existing {
m.watches[key] = []backingCallbackFunction{}
}
m.watches[key] = append(m.watches[key], callback)
return nil
}
func (m *memConfig) Close() {
}
// Mem creates a memory config
func Mem() ReaderWriter {
return &memConfig{
vals: make(map[string][]byte),
watches: make(map[string][]backingCallbackFunction),
}
}
// MemLoader is a helper for loading a memory conf
func MemLoader() BackingLoader {
return BackingLoaderFunc(func() (Reader, error) {
return Mem(), nil
})
}