9 // VarintSize returns the size (in bytes) of `num` encoded as a varint.
10 func VarintSize(num int) int {
11 bits := bits.Len(uint(num))
12 q, r := bits/7, bits%7
14 if r > 0 || size == 0 {
20 // CodeToVarint converts an integer to a varint-encoded []byte
21 func CodeToVarint(num int) []byte {
22 buf := make([]byte, VarintSize(num))
23 n := binary.PutUvarint(buf, uint64(num))
27 // VarintToCode converts a varint-encoded []byte to an integer protocol code
28 func VarintToCode(buf []byte) int {
29 num, _, err := ReadVarintCode(buf)
36 // ReadVarintCode reads a varint code from the beginning of buf.
37 // returns the code, and the number of bytes read.
38 func ReadVarintCode(buf []byte) (int, int, error) {
39 num, n := binary.Uvarint(buf)
41 return 0, 0, fmt.Errorf("varints larger than uint64 not yet supported")
43 return int(num), n, nil