From d462e342b73aed8a8737a9ef17bd78a21cd639a9 Mon Sep 17 00:00:00 2001 From: Cole Brown Date: Thu, 29 Nov 2018 18:58:36 -0500 Subject: [PATCH] Fix yet another bug in VarintSize, add test --- varint.go | 4 ++-- varint_test.go | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 varint_test.go diff --git a/varint.go b/varint.go index 0b8bf11..b8b1507 100644 --- a/varint.go +++ b/varint.go @@ -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] } diff --git a/varint_test.go b/varint_test.go new file mode 100644 index 0000000..db0b167 --- /dev/null +++ b/varint_test.go @@ -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) +}