-
Notifications
You must be signed in to change notification settings - Fork 83
/
entity.go
74 lines (65 loc) · 1.8 KB
/
entity.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
package event
import (
"sync"
)
var (
highestID CID
callers = make([]Entity, 0)
idMutex = sync.Mutex{}
)
// Parse returns the given cid, or the entity's cid
// if the given cid is 0. This way, multiple entities can be
// composed together by passing 0 down to lower tiered constructors, so that
// the topmost entity is stored once and bind functions will
// bind to the topmost entity.
func (cid CID) Parse(e Entity) CID {
if cid == 0 {
return e.Init()
}
return cid
}
// An Entity is an element which can be bound to,
// in that it has a CID. All Entities need to implement
// is an Init function which should call NextID(e) and
// return that id.
type Entity interface {
Init() CID
}
// NextID finds the next id (always incrementing)
// and returns it, after adding the given entity to
// the slice of callers at the returned index.
func NextID(e Entity) CID {
idMutex.Lock()
highestID++
callers = append(callers, e)
id := highestID
idMutex.Unlock()
return id
}
// GetEntity either returns callers[i-1]
// or nil, if there is nothing at that index.
func GetEntity(i int) interface{} {
if HasEntity(i) {
return callers[i-1]
}
return nil
}
// HasEntity returns whether the given caller id is an initialized entity
func HasEntity(i int) bool {
return len(callers) >= i && i != 0
}
// DestroyEntity sets the index within the caller list to nil. Note that this
// does not reduce the size of the caller list, a potential change in the
// future would be to A) use a map or B) reassign caller ids to not directly
// correspond to indices within callers
func DestroyEntity(i int) {
callers[i-1] = nil
}
// ResetEntities resets callers and highestID, effectively dropping the
// remaining entities from accessible memory.
func ResetEntities() {
idMutex.Lock()
highestID = 0
callers = []Entity{}
idMutex.Unlock()
}