-
Notifications
You must be signed in to change notification settings - Fork 79
/
ref_counter.go
71 lines (63 loc) · 1.26 KB
/
ref_counter.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
package vm
import (
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
)
// refCounter represents a reference counter for the VM.
type refCounter int
type (
rcInc interface {
IncRC() int
}
rcDec interface {
DecRC() int
}
)
func newRefCounter() *refCounter {
return new(refCounter)
}
// Add adds an item to the reference counter.
func (r *refCounter) Add(item stackitem.Item) {
if r == nil {
return
}
*r++
irc, ok := item.(rcInc)
if !ok || irc.IncRC() > 1 {
return
}
switch t := item.(type) {
case *stackitem.Array, *stackitem.Struct:
for _, it := range item.Value().([]stackitem.Item) {
r.Add(it)
}
case *stackitem.Map:
elems := t.Value().([]stackitem.MapElement)
for i := range elems {
r.Add(elems[i].Key)
r.Add(elems[i].Value)
}
}
}
// Remove removes an item from the reference counter.
func (r *refCounter) Remove(item stackitem.Item) {
if r == nil {
return
}
*r--
irc, ok := item.(rcDec)
if !ok || irc.DecRC() > 0 {
return
}
switch t := item.(type) {
case *stackitem.Array, *stackitem.Struct:
for _, it := range item.Value().([]stackitem.Item) {
r.Remove(it)
}
case *stackitem.Map:
elems := t.Value().([]stackitem.MapElement)
for i := range elems {
r.Remove(elems[i].Key)
r.Remove(elems[i].Value)
}
}
}