-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatastores.go
57 lines (45 loc) · 923 Bytes
/
datastores.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
package datastores
import "sync"
// DataStore ###########################
// Memory storage structures
//###########################
// Generic data store
type DataStore[K comparable, V any] struct {
sync.RWMutex
cache map[K]V
}
func NewDataStore[K comparable, V any]() *DataStore[K, V] {
return &DataStore[K, V]{
cache: make(map[K]V),
}
}
func (ds *DataStore[K, V]) Set(key K, value V) {
ds.Lock()
defer ds.Unlock()
ds.cache[key] = value
}
func (ds *DataStore[K, V]) Get(key K) V {
ds.RLock()
defer ds.RUnlock()
return ds.cache[key]
}
func (ds *DataStore[K, V]) SetAll(data map[K]V) {
ds.Lock()
defer ds.Unlock()
ds.cache = data
}
func (ds *DataStore[K, V]) GetAll() map[K]V {
ds.RLock()
defer ds.RUnlock()
return ds.cache
}
func (ds *DataStore[K, V]) Unset(key K) bool {
ds.Lock()
defer ds.Unlock()
_, ok := ds.cache[key]
if ok {
delete(ds.cache, key)
return true
}
return false
}