OSDN Git Service

add package
[bytom/vapor.git] / vendor / github.com / multiformats / go-multiaddr / varint.go
1 package multiaddr
2
3 import (
4         "encoding/binary"
5         "fmt"
6         "math/bits"
7 )
8
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
13         size := q
14         if r > 0 || size == 0 {
15                 size++
16         }
17         return size
18 }
19
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))
24         return buf[:n]
25 }
26
27 // VarintToCode converts a varint-encoded []byte to an integer protocol code
28 func VarintToCode(buf []byte) int {
29         num, _, err := ReadVarintCode(buf)
30         if err != nil {
31                 panic(err)
32         }
33         return num
34 }
35
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)
40         if n < 0 {
41                 return 0, 0, fmt.Errorf("varints larger than uint64 not yet supported")
42         }
43         return int(num), n, nil
44 }