-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassignment.go
65 lines (56 loc) · 1.13 KB
/
assignment.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
package magic
import (
"encoding/json"
"sync"
"time"
)
// a patch has the following format when it gets sent to the client
// [[templateID, TEMPLATE][socketID, templateID, DATA]]
type assignment struct {
socketid json.RawMessage
data map[string]any
}
type assignments struct {
p []*assignment
l sync.Mutex
onSend func(ps []*assignment)
}
func NewPatches(onSend func(ps []*assignment)) *assignments {
return &assignments{
p: []*assignment{},
l: sync.Mutex{},
onSend: onSend,
}
}
var patchPool = sync.Pool{
New: func() any {
return new(assignment)
},
}
func getAssignment() *assignment {
return patchPool.Get().(*assignment)
}
func (p *assignment) free() {
p.data = map[string]any{}
p.socketid = []byte{}
patchPool.Put(p)
}
func (ps *assignments) append(p ...*assignment) {
ps.l.Lock()
if len(ps.p) == 0 {
ps.p = append(ps.p, p...)
submitTask(ps.runSend)
} else {
ps.p = append(ps.p, p...)
}
ps.l.Unlock()
}
func (ps *assignments) runSend() {
time.Sleep(time.Millisecond)
ps.l.Lock()
cp := make([]*assignment, len(ps.p))
copy(cp, ps.p)
ps.p = []*assignment{}
ps.onSend(cp)
ps.l.Unlock()
}