-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPacket.go
379 lines (307 loc) · 8.48 KB
/
Packet.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package pktconn
import (
"encoding/binary"
"fmt"
"math"
"sync"
"sync/atomic"
"unsafe"
)
const (
minPayloadCap = 128
payloadCapGrowShift = uint(2)
)
var (
packetEndian = binary.LittleEndian
predefinePayloadCapacities []uint32
packetBufferPools = map[uint32]*sync.Pool{}
packetPool = &sync.Pool{
New: func() interface{} {
p := &Packet{}
p.bytes = p.initialBytes[:]
return p
},
}
)
func init() {
payloadCap := uint32(minPayloadCap) << payloadCapGrowShift
for payloadCap < MaxPayloadLength {
predefinePayloadCapacities = append(predefinePayloadCapacities, payloadCap)
payloadCap <<= payloadCapGrowShift
}
predefinePayloadCapacities = append(predefinePayloadCapacities, MaxPayloadLength)
for _, payloadCap := range predefinePayloadCapacities {
payloadCap := payloadCap
packetBufferPools[payloadCap] = &sync.Pool{
New: func() interface{} {
return make([]byte, prePayloadSize+payloadCap)
},
}
}
}
func getPayloadCapOfPayloadLen(payloadLen uint32) uint32 {
for _, payloadCap := range predefinePayloadCapacities {
if payloadCap >= payloadLen {
return payloadCap
}
}
return MaxPayloadLength
}
// Packet is a packet for sending data
type Packet struct {
Src *PacketConn
readCursor uint32
refcount int64
bytes []byte
initialBytes [prePayloadSize + minPayloadCap]byte
}
func allocPacket() *Packet {
pkt := packetPool.Get().(*Packet)
pkt.refcount = 1
if pkt.GetPayloadLen() != 0 {
panic(fmt.Errorf("allocPacket: payload should be 0, but is %d", pkt.GetPayloadLen()))
}
return pkt
}
// NewPacket allocates a new packet
func NewPacket() *Packet {
return allocPacket()
}
func (p *Packet) payloadSlice(i, j uint32) []byte {
return p.bytes[i+prePayloadSize : j+prePayloadSize]
}
// GetPayloadLen returns the payload length
func (p *Packet) GetPayloadLen() uint32 {
packetEndian.Uint32(p.bytes[0:4])
return *(*uint32)(unsafe.Pointer(&p.bytes[0]))
}
func (p *Packet) SetPayloadLen(plen uint32) {
pplen := (*uint32)(unsafe.Pointer(&p.bytes[0]))
*pplen = plen
}
// Payload returns the total payload of packet
func (p *Packet) Payload() []byte {
return p.bytes[prePayloadSize : prePayloadSize+p.GetPayloadLen()]
}
// UnreadPayload returns the unread payload
func (p *Packet) UnreadPayload() []byte {
pos := p.readCursor + prePayloadSize
payloadEnd := prePayloadSize + p.GetPayloadLen()
return p.bytes[pos:payloadEnd]
}
// HasUnreadPayload returns if all payload is read
func (p *Packet) HasUnreadPayload() bool {
pos := p.readCursor
plen := p.GetPayloadLen()
return pos < plen
}
func (p *Packet) data() []byte {
return p.bytes[0 : prePayloadSize+p.GetPayloadLen()]
}
// PayloadCap returns the current payload capacity
func (p *Packet) PayloadCap() uint32 {
return uint32(len(p.bytes) - prePayloadSize)
}
func (p *Packet) extendPayload(size int) []byte {
if size > MaxPayloadLength {
panic(ErrPayloadTooLarge)
}
payloadLen := p.GetPayloadLen()
newPayloadLen := payloadLen + uint32(size)
oldCap := p.PayloadCap()
if newPayloadLen <= oldCap { // most case
p.SetPayloadLen(newPayloadLen)
return p.payloadSlice(payloadLen, newPayloadLen)
}
if newPayloadLen > MaxPayloadLength {
panic(ErrPayloadTooLarge)
}
// try to find the proper capacity for the size bytes
resizeToCap := getPayloadCapOfPayloadLen(newPayloadLen)
buffer := packetBufferPools[resizeToCap].Get().([]byte)
if len(buffer) != int(resizeToCap+prePayloadSize) {
panic(fmt.Errorf("buffer size should be %d, but is %d", resizeToCap, len(buffer)))
}
copy(buffer, p.data())
oldBytes := p.bytes
p.bytes = buffer
if oldCap > minPayloadCap {
// release old bytes
packetBufferPools[oldCap].Put(oldBytes)
}
p.SetPayloadLen(newPayloadLen)
return p.payloadSlice(payloadLen, newPayloadLen)
}
// addRefCount adds reference count of packet
func (p *Packet) addRefCount(add int64) {
atomic.AddInt64(&p.refcount, add)
}
func (p *Packet) Retain() {
p.addRefCount(1)
}
// Release releases the packet to packet pool
func (p *Packet) Release() {
refcount := atomic.AddInt64(&p.refcount, -1)
if refcount == 0 {
p.Src = nil
payloadCap := p.PayloadCap()
if payloadCap > minPayloadCap {
buffer := p.bytes
p.bytes = p.initialBytes[:]
packetBufferPools[payloadCap].Put(buffer) // reclaim the buffer
}
p.readCursor = 0
p.SetPayloadLen(0)
packetPool.Put(p)
} else if refcount < 0 {
panic(fmt.Errorf("releasing packet with refcount=%d", p.refcount))
}
}
// ClearPayload clears packet payload
func (p *Packet) ClearPayload() {
p.readCursor = 0
p.SetPayloadLen(0)
}
func (p *Packet) SetReadPos(pos uint32) {
plen := p.GetPayloadLen()
if pos > plen {
pos = plen
}
p.readCursor = pos
}
func (p *Packet) GetReadPos() uint32 {
return p.readCursor
}
// WriteOneByte appends one byte to the end of payload
func (p *Packet) WriteOneByte(b byte) {
pl := p.extendPayload(1)
pl[0] = b
}
// WriteBool appends one byte 1/0 to the end of payload
func (p *Packet) WriteBool(b bool) {
if b {
p.WriteOneByte(1)
} else {
p.WriteOneByte(0)
}
}
// WriteUint16 appends one uint16 to the end of payload
func (p *Packet) WriteUint16(v uint16) {
pl := p.extendPayload(2)
packetEndian.PutUint16(pl, v)
}
func (p *Packet) WriteInt16(v int16) {
p.WriteUint16(uint16(v))
}
// WriteUint32 appends one uint32 to the end of payload
func (p *Packet) WriteUint32(v uint32) {
pl := p.extendPayload(4)
packetEndian.PutUint32(pl, v)
}
func (p *Packet) WriteInt32(v int32) {
p.WriteUint32(uint32(v))
}
// WriteUint64 appends one uint64 to the end of payload
func (p *Packet) WriteUint64(v uint64) {
pl := p.extendPayload(8)
packetEndian.PutUint64(pl, v)
}
func (p *Packet) WriteInt64(v int64) {
p.WriteUint64(uint64(v))
}
// WriteFloat32 appends one float32 to the end of payload
func (p *Packet) WriteFloat32(f float32) {
p.WriteUint32(math.Float32bits(f))
}
// ReadFloat32 reads one float32 from the beginning of unread payload
func (p *Packet) ReadFloat32() float32 {
return math.Float32frombits(p.ReadUint32())
}
// WriteFloat64 appends one float64 to the end of payload
func (p *Packet) WriteFloat64(f float64) {
p.WriteUint64(math.Float64bits(f))
}
// ReadFloat64 reads one float64 from the beginning of unread payload
func (p *Packet) ReadFloat64() float64 {
return math.Float64frombits(p.ReadUint64())
}
// WriteBytes appends slice of bytes to the end of payload
func (p *Packet) WriteBytes(b []byte) {
pl := p.extendPayload(len(b))
copy(pl, b)
}
// WriteVarBytesI appends varsize bytes to the end of payload
func (p *Packet) WriteVarBytesI(b []byte) {
p.WriteUint32(uint32(len(b)))
p.WriteBytes(b)
}
// WriteVarBytesH appends varsize bytes to the end of payload
func (p *Packet) WriteVarBytesH(b []byte) {
if len(b) > 0xFFFF {
panic(ErrPayloadTooLarge)
}
p.WriteUint16(uint16(len(b)))
p.WriteBytes(b)
}
func (p *Packet) WriteVarStrI(s string) {
p.WriteVarBytesI([]byte(s))
}
func (p *Packet) WriteVarStrH(s string) {
p.WriteVarBytesH([]byte(s))
}
// ReadOneByte reads one byte from the beginning
func (p *Packet) ReadOneByte() (v byte) {
pos := p.readCursor + prePayloadSize
v = p.bytes[pos]
p.readCursor += 1
return
}
// ReadBool reads one byte 1/0 from the beginning of unread payload
func (p *Packet) ReadBool() (v bool) {
return p.ReadOneByte() != 0
}
// ReadBytes reads bytes from the beginning of unread payload
func (p *Packet) ReadBytes(size int) []byte {
readPos := p.readCursor
readEnd := readPos + uint32(size)
if size > MaxPayloadLength || readEnd > p.GetPayloadLen() {
panic(ErrPayloadTooSmall)
}
p.readCursor = readEnd
return p.payloadSlice(readPos, readEnd)
}
// ReadUint16 reads one uint16 from the beginning of unread payload
func (p *Packet) ReadUint16() uint16 {
return packetEndian.Uint16(p.ReadBytes(2))
}
func (p *Packet) ReadInt16() int16 {
return int16(p.ReadUint16())
}
// ReadUint32 reads one uint32 from the beginning of unread payload
func (p *Packet) ReadUint32() uint32 {
return packetEndian.Uint32(p.ReadBytes(4))
}
func (p *Packet) ReadInt32() int32 {
return int32(p.ReadUint32())
}
// ReadUint64 reads one uint64 from the beginning of unread payload
func (p *Packet) ReadUint64() (v uint64) {
return packetEndian.Uint64(p.ReadBytes(8))
}
func (p *Packet) ReadInt64() int64 {
return int64(p.ReadUint64())
}
func (p *Packet) ReadVarBytesI() []byte {
bl := p.ReadUint32()
return p.ReadBytes(int(bl))
}
func (p *Packet) ReadVarBytesH() []byte {
bl := p.ReadUint16()
return p.ReadBytes(int(bl))
}
func (p *Packet) ReadVarStrI() string {
return string(p.ReadVarBytesI())
}
func (p *Packet) ReadVarStrH() string {
return string(p.ReadVarBytesH())
}