-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
132 lines (116 loc) · 1.98 KB
/
stack.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package KRMM
import (
"sync"
)
type Stack struct {
l sync.RWMutex
prev *Stack
layers []*Layer
}
func (s *Stack) QueryScope(key string) *Element {
return s.query(key, true)
}
func (s *Stack) QueryGlobal(key string) *Element {
return s.query(key, false)
}
func (s *Stack) query(key string, stopAtStackFrame bool) *Element {
if s == nil {
return nil
}
s.l.RLock()
defer s.l.RUnlock()
for i := len(s.layers) - 1; i >= 0; i-- {
layer := s.layers[i]
switch layer.Type() {
case LayerType_StackFrame:
if stopAtStackFrame {
return nil
}
default:
elem, _ := layer.m.Get(key)
if elem != nil {
return elem
}
}
}
if s.prev != nil {
return s.prev.query(key, stopAtStackFrame)
}
return nil
}
func (s *Stack) Fork() *Stack {
return &Stack{
prev: s,
}
}
func (s *Stack) Push(layer *Layer) {
s.l.Lock()
defer s.l.Unlock()
s.layers = append(s.layers, layer)
}
func (s *Stack) PushFrame() {
s.Push(NewLayer(LayerType_StackFrame))
}
func (s *Stack) Top() *Layer {
s.l.RLock()
defer s.l.RUnlock()
t := s._top()
if t != nil {
return t
}
if s.prev != nil {
return s.prev.Top()
}
return nil
}
func (s *Stack) SelfTop() *Layer {
s.l.RLock()
defer s.l.RUnlock()
return s._top()
}
func (s *Stack) _top() *Layer {
if len(s.layers) == 0 {
return nil
}
return s.layers[len(s.layers)-1]
}
func (s *Stack) Pop() *Layer {
s.l.Lock()
defer s.l.Unlock()
if len(s.layers) == 0 {
return nil
}
layer := s.layers[len(s.layers)-1]
s._pop()
return layer
}
func (s *Stack) _pop() {
if len(s.layers) == 0 {
return
}
s.layers = s.layers[:len(s.layers)-1]
}
func (s *Stack) PopFrame() {
s.l.Lock()
defer s.l.Unlock()
if len(s.layers) == 0 {
return
}
for len(s.layers) > 0 && s._top().Type() != LayerType_StackFrame {
s._pop()
}
if len(s.layers) == 0 {
return
}
s._pop()
}
func (s *Stack) Raw() []*Layer {
s.l.RLock()
defer s.l.RUnlock()
return s.layers
}
func (s *Stack) Len() int {
s.l.RLock()
defer s.l.RUnlock()
return len(s.layers)
}