-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathnq_payload_test.go
61 lines (49 loc) · 1.32 KB
/
nq_payload_test.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
package nq_test
import (
"encoding/binary"
"hash/crc64"
"math/rand"
"sync"
"testing"
"time"
)
type testMsg []byte
var crcTable = crc64.MakeTable(crc64.ECMA)
const (
timestampLen = 8 // int64
checksumLen = 8 // uint64
minPayload = 80
maxPayload = 250
)
func newTestMsg() *testMsg {
length := minPayload + rand.Intn(maxPayload-minPayload)
data := make([]byte, length+timestampLen+checksumLen)
rand.Read(data[timestampLen+checksumLen:])
binary.LittleEndian.PutUint64(data[timestampLen:], crc64.Checksum(data[timestampLen+checksumLen:], crcTable))
m := testMsg(data)
m.SetTimestamp()
return &m
}
var testMsgPool = sync.Pool{New: func() interface{} { return newTestMsg() }}
func (m *testMsg) Age() time.Duration {
ns := binary.LittleEndian.Uint64(m.Raw())
return time.Since(time.Unix(0, int64(ns)))
}
func (m *testMsg) SetTimestamp() {
binary.LittleEndian.PutUint64(m.Raw(), uint64(time.Now().UnixNano()))
}
func (m *testMsg) Checksum() uint64 {
return binary.LittleEndian.Uint64(m.Raw()[timestampLen:])
}
func (m *testMsg) Ok() bool {
data := m.Raw()[timestampLen+checksumLen:]
return crc64.Checksum(data, crcTable) == m.Checksum()
}
func (m *testMsg) Raw() []byte { return []byte(*m) }
func TestTestMsgChecksum(t *testing.T) {
p := testMsgPool.Get().(*testMsg)
if !p.Ok() {
t.Fail()
}
testMsgPool.Put(p)
}