-
Notifications
You must be signed in to change notification settings - Fork 15
/
InstanceList.go
86 lines (71 loc) · 1.86 KB
/
InstanceList.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 datamodel
import (
"errors"
)
// TODO: Should work with PeerID
type instanceScope struct {
Instances map[uint32]*Instance
}
type InstanceList struct {
scopes map[string]*instanceScope
}
var ErrNullInstance = errors.New("instance is null")
var ErrInstanceDoesntExist = errors.New("instance doesn't exist")
func newInstanceScope() *instanceScope {
return &instanceScope{
Instances: make(map[uint32]*Instance),
}
}
func NewInstanceList() *InstanceList {
return &InstanceList{scopes: make(map[string]*instanceScope)}
}
func (s *instanceScope) remove(id uint32) {
delete(s.Instances, id)
}
func (l *InstanceList) getScope(ref Reference) *instanceScope {
scope, ok := l.scopes[ref.Scope]
if !ok {
scope = newInstanceScope()
l.scopes[ref.Scope] = scope
}
return scope
}
func (l *InstanceList) CreateInstance(ref Reference) (*Instance, error) {
if ref.IsNull {
return nil, ErrNullInstance
}
instance := l.getScope(ref).Instances[ref.Id]
if instance == nil {
instance, _ = NewInstance("", nil)
instance.Ref = ref
l.AddInstance(ref, instance)
return instance, nil
}
// Allow rebinds. I don't know if this is right, but it can't hurt, right?
return instance, nil
}
func (l *InstanceList) TryGetInstance(ref Reference) (*Instance, error) {
if ref.IsNull {
return nil, nil
}
instance := l.getScope(ref).Instances[ref.Id]
if instance == nil {
return nil, ErrInstanceDoesntExist
}
return instance, nil
}
func (l *InstanceList) AddInstance(ref Reference, instance *Instance) {
l.getScope(ref).Instances[ref.Id] = instance
}
func (l *InstanceList) Populate(instances []*Instance) {
for _, inst := range instances {
l.AddInstance(inst.Ref, inst)
l.Populate(inst.Children)
}
}
func (l *InstanceList) RemoveTree(instance *Instance) {
l.getScope(instance.Ref).remove(instance.Ref.Id)
for _, child := range instance.Children {
l.RemoveTree(child)
}
}