forked from segmentio/kafka-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crc32.go
80 lines (68 loc) · 1.44 KB
/
crc32.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
package kafka
import (
"bytes"
"encoding/binary"
"hash/crc32"
"sync"
)
func crc32OfMessage(magicByte int8, attributes int8, timestamp int64, key []byte, value []byte) uint32 {
b := acquireCrc32Buffer()
b.writeInt8(magicByte)
b.writeInt8(attributes)
if magicByte != 0 {
b.writeInt64(timestamp)
}
b.writeBytes(key)
b.writeBytes(value)
sum := b.sum
releaseCrc32Buffer(b)
return sum
}
type crc32Buffer struct {
sum uint32
buf bytes.Buffer
}
func (c *crc32Buffer) writeInt8(i int8) {
c.buf.Truncate(0)
c.buf.WriteByte(byte(i))
c.update()
}
func (c *crc32Buffer) writeInt32(i int32) {
a := [4]byte{}
binary.BigEndian.PutUint32(a[:], uint32(i))
c.buf.Truncate(0)
c.buf.Write(a[:])
c.update()
}
func (c *crc32Buffer) writeInt64(i int64) {
a := [8]byte{}
binary.BigEndian.PutUint64(a[:], uint64(i))
c.buf.Truncate(0)
c.buf.Write(a[:])
c.update()
}
func (c *crc32Buffer) writeBytes(b []byte) {
if b == nil {
c.writeInt32(-1)
} else {
c.writeInt32(int32(len(b)))
}
c.sum = crc32Update(c.sum, b)
}
func (c *crc32Buffer) update() {
c.sum = crc32Update(c.sum, c.buf.Bytes())
}
func crc32Update(sum uint32, b []byte) uint32 {
return crc32.Update(sum, crc32.IEEETable, b)
}
var crc32BufferPool = sync.Pool{
New: func() interface{} { return &crc32Buffer{} },
}
func acquireCrc32Buffer() *crc32Buffer {
c := crc32BufferPool.Get().(*crc32Buffer)
c.sum = 0
return c
}
func releaseCrc32Buffer(b *crc32Buffer) {
crc32BufferPool.Put(b)
}