-
Notifications
You must be signed in to change notification settings - Fork 3
/
state_overlay.go
60 lines (46 loc) · 1010 Bytes
/
state_overlay.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
package ogimpl
import (
"sync"
"github.com/symphony09/ograph/ogcore"
)
type OverlayState struct {
Upper map[any]any
Lower ogcore.State
sync.RWMutex
}
func (state *OverlayState) Get(key any) (any, bool) {
state.RLock()
defer state.RUnlock()
if val, ok := state.Upper[key]; ok {
return val, ok
}
return state.Lower.Get(key)
}
func (state *OverlayState) Set(key any, val any) {
state.Lock()
defer state.Unlock()
state.Upper[key] = val
}
func (state *OverlayState) Update(key any, updateFunc func(val any) any) {
state.Lock()
defer state.Unlock()
if val, ok := state.Upper[key]; ok {
state.Upper[key] = updateFunc(val)
} else {
val, _ := state.Lower.Get(key)
state.Upper[key] = updateFunc(val)
}
}
func (state *OverlayState) Sync() {
for k, v := range state.Upper {
state.Lower.Set(k, v)
delete(state.Upper, k)
}
}
func NewOverlayState(state ogcore.State) *OverlayState {
overState := &OverlayState{
Upper: make(map[any]any),
Lower: state,
}
return overState
}