-
Notifications
You must be signed in to change notification settings - Fork 0
/
buf.go
53 lines (44 loc) · 906 Bytes
/
buf.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
package rkive
import (
"encoding/binary"
"sync"
)
var bufPool *sync.Pool
func init() {
bufPool = new(sync.Pool)
bufPool.New = func() interface{} {
return &buf{Body: make([]byte, 512)}
}
}
type buf struct {
Body []byte
}
// proto message w/ Size and MarshalTo
type protom interface {
MarshalTo([]byte) (n int, err error)
Size() int
}
// opportunistic MarshalTo; leaves Body[4] open for code
func (b *buf) Set(p protom) error {
sz := p.Size()
bsz := sz + 5
if cap(b.Body) >= bsz {
b.Body = b.Body[0:bsz]
} else {
b.Body = make([]byte, bsz)
}
binary.BigEndian.PutUint32(b.Body, uint32(sz+1))
_, err := p.MarshalTo(b.Body[5:])
return err
}
func (b *buf) setSz(n int) {
if cap(b.Body) >= n {
b.Body = b.Body[0:n]
} else {
b.Body = make([]byte, n)
}
}
func getBuf() *buf {
return bufPool.Get().(*buf)
}
func putBuf(b *buf) { b.Body = b.Body[:cap(b.Body)]; bufPool.Put(b) }