Commit d462e342 authored by Cole Brown's avatar Cole Brown

Fix yet another bug in VarintSize, add test

parent 1a8ba091
......@@ -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]
}
......
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)
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment