-
Notifications
You must be signed in to change notification settings - Fork 6
/
message_fragment_headers.go
101 lines (84 loc) · 2.26 KB
/
message_fragment_headers.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
package secureio
import (
"encoding/binary"
"sync"
)
var (
messageFragmentHeadersSize = uint(binary.Size(messageFragmentHeadersData{}))
)
type messageFragmentHeaders struct {
messageFragmentHeadersData
pool *messageFragmentHeadersPool
isBusy bool
}
type messageFragmentHeadersData struct {
ChainID uint64
StartPos uint64
TotalMessageLength uint64
}
type messageFragmentHeadersPool struct {
storage sync.Pool
}
func newMessageFragmentHeadersPool() *messageFragmentHeadersPool {
pool := &messageFragmentHeadersPool{}
pool.storage.New = func() interface{} {
msg := &messageFragmentHeaders{
pool: pool,
}
return msg
}
return pool
}
func (hdr *messageFragmentHeadersData) Set(chainID, startPos, totalLength uint64) {
hdr.ChainID = chainID
hdr.StartPos = startPos
hdr.TotalMessageLength = totalLength
}
func (pool *messageFragmentHeadersPool) AcquireMessageFragmentHeaders() *messageFragmentHeaders {
hdr := pool.storage.Get().(*messageFragmentHeaders)
if hdr.isBusy {
panic(`should not happened`)
}
hdr.isBusy = true
return hdr
}
func (hdr *messageFragmentHeadersData) Write(b []byte) (int, error) {
if uint(len(b)) < messageFragmentHeadersSize {
return 0, newErrTooShort(messageFragmentHeadersSize, uint(len(b)))
}
binaryOrderType.PutUint64(b[0:], hdr.ChainID)
b = b[8:]
binaryOrderType.PutUint64(b[0:], hdr.StartPos)
b = b[8:]
binaryOrderType.PutUint64(b[0:], hdr.TotalMessageLength)
b = b[8:]
return int(messageFragmentHeadersSize), nil
}
func (hdr *messageFragmentHeadersData) Read(b []byte) (int, error) {
if uint(len(b)) < messageFragmentHeadersSize {
return 0, newErrTooShort(messageFragmentHeadersSize, uint(len(b)))
}
hdr.ChainID = binaryOrderType.Uint64(b[0:])
b = b[8:]
hdr.StartPos = binaryOrderType.Uint64(b[0:])
b = b[8:]
hdr.TotalMessageLength = binaryOrderType.Uint64(b[0:])
b = b[8:]
return int(messageFragmentHeadersSize), nil
}
func (pool *messageFragmentHeadersPool) Put(hdr *messageFragmentHeaders) {
if hdr == nil || !hdr.isBusy {
panic(`should not happened`)
}
hdr.Reset()
hdr.isBusy = false
pool.storage.Put(hdr)
}
func (hdr *messageFragmentHeaders) Reset() {
hdr.ChainID = 0
hdr.StartPos = 0
hdr.TotalMessageLength = 0
}
func (hdr *messageFragmentHeaders) Release() {
hdr.pool.Put(hdr)
}