forked from hashicorp/consul-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
brain.go
74 lines (59 loc) · 1.87 KB
/
brain.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
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"sync"
dep "github.com/hashicorp/consul-template/dependency"
)
// Brain is what Template uses to determine the values that are
// available for template parsing.
type Brain struct {
sync.RWMutex
// data is the map of individual dependencies (by HashCode()) and the most
// recent data for that dependency.
data map[string]interface{}
// receivedData is an internal tracker of which dependencies have stored data
// in the brain.
receivedData map[string]struct{}
}
// NewBrain creates a new Brain with empty values for each
// of the key structs.
func NewBrain() *Brain {
return &Brain{
data: make(map[string]interface{}),
receivedData: make(map[string]struct{}),
}
}
// Remember accepts a dependency and the data to store associated with that
// dep. This function converts the given data to a proper type and stores
// it interally.
func (b *Brain) Remember(d dep.Dependency, data interface{}) {
b.Lock()
defer b.Unlock()
b.data[d.HashCode()] = data
b.receivedData[d.HashCode()] = struct{}{}
}
// Recall gets the current value for the given dependency in the Brain.
func (b *Brain) Recall(d dep.Dependency) (interface{}, bool) {
b.RLock()
defer b.RUnlock()
// If we have not received data for this dependency, return now.
if _, ok := b.receivedData[d.HashCode()]; !ok {
return nil, false
}
return b.data[d.HashCode()], true
}
// ForceSet is used to force set the value of a dependency
// for a given hash code
func (b *Brain) ForceSet(hashCode string, data interface{}) {
b.Lock()
defer b.Unlock()
b.data[hashCode] = data
b.receivedData[hashCode] = struct{}{}
}
// Forget accepts a dependency and removes all associated data with this
// dependency. It also resets the "receivedData" internal map.
func (b *Brain) Forget(d dep.Dependency) {
b.Lock()
defer b.Unlock()
delete(b.data, d.HashCode())
delete(b.receivedData, d.HashCode())
}