-
Notifications
You must be signed in to change notification settings - Fork 2
/
syncdict.go
83 lines (69 loc) · 1.8 KB
/
syncdict.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
75
76
77
78
79
80
81
82
83
package dictionary
import (
"fmt"
"strings"
"sync"
)
// SyncDict is a string map Dictionary to do simple key-value replacements. It is goro-safe for updates, and optimized for read-mostly implementations.
type SyncDict struct {
dict sync.Map
lock sync.Mutex
}
// AddValues adds the key/value pairs listed to the the SyncDict
func (m *SyncDict) AddValues(values map[string]string) {
m.lock.Lock()
defer m.lock.Unlock()
for k, v := range values {
m.dict.Store(k, v)
}
}
// Resolve walks the dictionary and updates any values that contain macros with static strings.
func (m *SyncDict) Resolve() {
m.lock.Lock()
defer m.lock.Unlock()
m.dict.Range(func(key, value interface{}) bool {
if strings.Contains(value.(string), "%%") {
m.dict.Store(key, m.Replacer(value.(string)))
}
return true
})
}
// Replacer takes a string, and expands any %%-prefixed strings registered as macros, with their corresponding values
func (m *SyncDict) Replacer(in string) string {
var (
out = in
replaced bool
c int
)
for {
out, replaced = m.replacer(out)
if !replaced || c > 20 {
// We're done, or circuit breaker popped
break
}
c++
}
return out
}
// replacer takes a string, and expands any %%-prefixed strings registered as macros, with their corresponding values, returning false when there was nothing to replace
func (m *SyncDict) replacer(in string) (string, bool) {
if !strings.Contains(in, "%%") {
// Don't waste energy
return in, false
}
out := in
rep := false
m.dict.Range(func(key, value interface{}) bool {
before := out
out = strings.Replace(out, fmt.Sprintf("%s%s", "%%", key.(string)), value.(string), -1)
if before != out {
rep = true
}
if !strings.Contains(out, "%%") {
// Let's be done here
return false
}
return true
})
return out, rep
}