-
Notifications
You must be signed in to change notification settings - Fork 0
/
send_queue.go
58 lines (50 loc) · 1.11 KB
/
send_queue.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
package spectral
import (
"sync"
"github.com/cooldogedev/spectral/internal/frame"
"github.com/cooldogedev/spectral/internal/protocol"
)
const packetSize = protocol.MaxPacketSize - protocol.PacketHeaderSize
type sendQueue struct {
connectionID protocol.ConnectionID
sequenceID uint32
pk []byte
list [][]byte
cond *sync.Cond
mu sync.Mutex
}
func newSendQueue(connectionID protocol.ConnectionID) *sendQueue {
s := &sendQueue{
connectionID: connectionID,
sequenceID: 1,
pk: make([]byte, 0, packetSize),
}
s.cond = sync.NewCond(&s.mu)
return s
}
func (s *sendQueue) add(p []byte) {
s.mu.Lock()
s.list = append(s.list, p)
s.mu.Unlock()
s.cond.Signal()
}
func (s *sendQueue) shift() (uint32, []byte) {
s.mu.Lock()
defer func() {
s.pk = s.pk[:0]
s.sequenceID++
s.mu.Unlock()
}()
var total uint32
for len(s.list) > 0 {
entry := s.list[0]
if len(s.pk)+len(entry) > packetSize {
break
}
s.list[0] = nil
s.list = s.list[1:]
s.pk = append(s.pk, entry...)
total++
}
return s.sequenceID, frame.Pack(s.connectionID, s.sequenceID, total, s.pk)
}