Merge pull request #88 from bigs/bug/varintsize

Fix bug in VarintSize
This commit is contained in:
Steven Allen 2018-11-29 16:16:22 -08:00 committed by GitHub
commit 0523e08ac1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 2 deletions

View File

@ -8,12 +8,18 @@ import (
// VarintSize returns the size (in bytes) of `num` encoded as a varint. // VarintSize returns the size (in bytes) of `num` encoded as a varint.
func VarintSize(num int) int { func VarintSize(num int) int {
return bits.Len(uint(num))/7 + 1 bits := bits.Len(uint(num))
q, r := bits/7, bits%7
size := q
if r > 0 || size == 0 {
size++
}
return size
} }
// CodeToVarint converts an integer to a varint-encoded []byte // CodeToVarint converts an integer to a varint-encoded []byte
func CodeToVarint(num int) []byte { func CodeToVarint(num int) []byte {
buf := make([]byte, bits.Len(uint(num))/7+1) buf := make([]byte, VarintSize(num))
n := binary.PutUvarint(buf, uint64(num)) n := binary.PutUvarint(buf, uint64(num))
return buf[:n] return buf[:n]
} }

23
varint_test.go Normal file
View File

@ -0,0 +1,23 @@
package multiaddr
import (
"encoding/binary"
"testing"
)
func checkVarint(t *testing.T, x int) {
buf := make([]byte, binary.MaxVarintLen64)
expected := binary.PutUvarint(buf, uint64(x))
size := VarintSize(x)
if size != expected {
t.Fatalf("expected varintsize of %d to be %d, got %d", x, expected, size)
}
}
func TestVarintSize(t *testing.T) {
max := 1 << 16
for x := 0; x < max; x++ {
checkVarint(t, x)
}
}