-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
94 lines (76 loc) · 1.86 KB
/
store.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
84
85
86
87
88
89
90
91
92
93
94
package store
import (
"strings"
"sync"
)
// CStore stands for ConcurrentStore and is simply an abstract of a map with a mutex.
type CStore struct {
mu sync.RWMutex
store map[string]string
}
// New returns an initialized CStore
func New() CStore {
return CStore{
store: make(map[string]string),
}
}
// Store stores the value with the provided key
func (cs *CStore) Store(key, value string) {
cs.mu.Lock()
cs.store[key] = value
cs.mu.Unlock()
}
// Load loads the value saved by the provided key.
func (cs *CStore) Load(key string) (string, bool) {
cs.mu.RLock()
val, ok := cs.store[key]
cs.mu.RUnlock()
return val, ok
}
// Contains checks if a key exists in the store.
func (cs *CStore) Contains(key string) bool {
_, ok := cs.Load(key)
return ok
}
// AnyContains checks whether the passed needle is contained
// in any of the keys that the store has.
func (cs *CStore) AnyContains(needle string) bool {
for key := range cs.store {
if strings.Contains(key, needle) {
return true
}
}
return false
}
// AnyContainsReverse checks whether any of the keys stored by
// the store is contained in the passed haystack
func (cs *CStore) AnyContainsReverse(haystack string) bool {
for key := range cs.store {
if strings.Contains(haystack, key) {
return true
}
}
return false
}
// StoreKey simply stores the key with empty value
func (cs *CStore) StoreKey(key string) {
cs.Store(key, "")
}
// Delete deletes an entry from the underlying map
func (cs *CStore) Delete(key string) {
cs.mu.Lock()
delete(cs.store, key)
cs.mu.Unlock()
}
// Size returns the size of the underlying map
func (cs *CStore) Size() int {
return len(cs.store)
}
// ToMap creates a copy of the underlying map and returns it
func (cs *CStore) ToMap() map[string]string {
newMap := make(map[string]string, len(cs.store))
for k, v := range cs.store {
newMap[k] = v
}
return newMap
}