-
Notifications
You must be signed in to change notification settings - Fork 2
/
scope_cache.go
86 lines (71 loc) · 1.68 KB
/
scope_cache.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
package goen
import (
"reflect"
"sync"
)
type ScopeCache struct {
Meta *MetaSchema
mu sync.RWMutex
data map[string]interface{}
}
func NewScopeCache(meta *MetaSchema) *ScopeCache {
return &ScopeCache{
Meta: meta,
data: map[string]interface{}{},
}
}
func (sc *ScopeCache) GetObject(rowKey RowKey) interface{} {
sc.mu.RLock()
defer sc.mu.RUnlock()
key, err := sc.Meta.KeyStringFromRowKey(rowKey)
if err != nil {
panic("goen: failed to get key string: " + err.Error())
}
return sc.data[key]
}
func (sc *ScopeCache) AddObject(v interface{}) {
sc.mu.Lock()
defer sc.mu.Unlock()
pk, refes := sc.Meta.RowKeysOf(v)
key, err := sc.Meta.KeyStringFromRowKey(pk)
if err != nil {
panic("goen: failed to get key string: " + err.Error())
}
sc.data[key] = v
for _, refe := range refes {
if reflect.DeepEqual(refe, pk) {
continue
}
key, err := sc.Meta.KeyStringFromRowKey(refe)
if err != nil {
panic("goen: failed to get key string: " + err.Error())
}
var slice []interface{}
if cached, ok := sc.data[key]; ok {
slice = cached.([]interface{})
}
sc.data[key] = append(slice, v)
}
}
func (sc *ScopeCache) HasObject(rowKey RowKey) bool {
sc.mu.RLock()
defer sc.mu.RUnlock()
key, err := sc.Meta.KeyStringFromRowKey(rowKey)
if err != nil {
panic("goen: failed to get key string: " + err.Error())
}
_, ok := sc.data[key]
return ok
}
func (sc *ScopeCache) RemoveObject(v interface{}) {
sc.mu.Lock()
defer sc.mu.Unlock()
pk, refes := sc.Meta.RowKeysOf(v)
for _, rowKey := range append(refes, pk) {
key, err := sc.Meta.KeyStringFromRowKey(rowKey)
if err != nil {
panic("goen: failed to get key string: " + err.Error())
}
delete(sc.data, key)
}
}