forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto.go
39 lines (34 loc) · 767 Bytes
/
proto.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
package x
import (
"encoding/binary"
)
type ProtoMessage interface {
Size() int
MarshalTo([]byte) (int, error)
}
func AppendProtoMsg(p []byte, msg ProtoMessage) ([]byte, error) {
sz := msg.Size()
p = ReserveCap(p, len(p)+sz)
buf := p[len(p) : len(p)+sz]
n, err := msg.MarshalTo(buf)
AssertTrue(sz == n)
return p[:len(p)+sz], err
}
func AppendUvarint(p []byte, x uint64) []byte {
p = ReserveCap(p, len(p)+binary.MaxVarintLen64)
buf := p[len(p) : len(p)+binary.MaxVarintLen64]
n := binary.PutUvarint(buf, x)
return p[:len(p)+n]
}
func ReserveCap(p []byte, atLeast int) []byte {
if cap(p) >= atLeast {
return p
}
newCap := cap(p) * 2
if newCap < atLeast {
newCap = atLeast
}
newP := make([]byte, len(p), newCap)
copy(newP, p)
return newP
}