mirror of
https://github.com/logos-messaging/go-multiaddr.git
synced 2026-01-04 05:53:05 +00:00
Fix yet another bug in VarintSize, add test
This commit is contained in:
parent
1a8ba0918f
commit
d462e342b7
@ -11,7 +11,7 @@ func VarintSize(num int) int {
|
|||||||
bits := bits.Len(uint(num))
|
bits := bits.Len(uint(num))
|
||||||
q, r := bits/7, bits%7
|
q, r := bits/7, bits%7
|
||||||
size := q
|
size := q
|
||||||
if r > 0 {
|
if r > 0 || size == 0 {
|
||||||
size++
|
size++
|
||||||
}
|
}
|
||||||
return size
|
return size
|
||||||
@ -19,7 +19,7 @@ func VarintSize(num int) int {
|
|||||||
|
|
||||||
// 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]
|
||||||
}
|
}
|
||||||
|
|||||||
16
varint_test.go
Normal file
16
varint_test.go
Normal 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)
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user