Fix yet another bug in VarintSize, add test

This commit is contained in:
Cole Brown 2018-11-29 18:58:36 -05:00
parent 1a8ba0918f
commit d462e342b7
2 changed files with 18 additions and 2 deletions

View File

@ -11,7 +11,7 @@ func VarintSize(num int) int {
bits := bits.Len(uint(num))
q, r := bits/7, bits%7
size := q
if r > 0 {
if r > 0 || size == 0 {
size++
}
return size
@ -19,7 +19,7 @@ func VarintSize(num int) int {
// CodeToVarint converts an integer to a varint-encoded []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))
return buf[:n]
}

16
varint_test.go Normal file
View File

@ -0,0 +1,16 @@
package multiaddr
import "testing"
func expectVarint(t *testing.T, x, expected int) {
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) {
expectVarint(t, (1<<7)-1, 1)
expectVarint(t, 0, 1)
expectVarint(t, 1<<7, 2)
}