Skip to content

Commit

Permalink
Add tests and fix conditional.
Browse files Browse the repository at this point in the history
  • Loading branch information
notbdu committed Jan 19, 2019
1 parent ea1a54e commit af02562
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 9 deletions.
18 changes: 9 additions & 9 deletions x/io/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,31 +66,31 @@ func ReadVarint(data []byte) (n int64, bytesRead int, err error) {

// VarintBytes returns the number of bytes required to encode a varint.
func VarintBytes(v int64) int {
if v < one || v >= -one {
if v < one && v >= -one {
return 1
}
if v < two || v >= -two {
if v < two && v >= -two {
return 2
}
if v < three || v >= -three {
if v < three && v >= -three {
return 3
}
if v < four || v >= -four {
if v < four && v >= -four {
return 4
}
if v < five || v >= -five {
if v < five && v >= -five {
return 5
}
if v < six || v >= -six {
if v < six && v >= -six {
return 6
}
if v < seven || v >= -seven {
if v < seven && v >= -seven {
return 7
}
if v < eight || v >= -eight {
if v < eight && v >= -eight {
return 8
}
if v < nine || v >= -nine {
if v < nine && v >= -nine {
return 9
}
return binary.MaxVarintLen64
Expand Down
41 changes: 41 additions & 0 deletions x/io/int_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package io

import (
"encoding/binary"
"math"
"testing"

"github.com/stretchr/testify/require"
)

func TestVarintBytes(t *testing.T) {
buf := make([]byte, binary.MaxVarintLen64)
lowerBounds := []int64{
-one,
-two,
-three,
-four,
-five,
-six,
-seven,
-eight,
-nine,
}
upperBounds := []int64{
one - 1,
two - 1,
three - 1,
four - 1,
five - 1,
six - 1,
seven - 1,
eight - 1,
nine - 1,
}
for idx := 0; idx < len(upperBounds); idx++ {
require.Equal(t, binary.PutVarint(buf, upperBounds[idx]), VarintBytes(upperBounds[idx]))
require.Equal(t, binary.PutVarint(buf, lowerBounds[idx]), VarintBytes(lowerBounds[idx]))
}
require.Equal(t, binary.PutVarint(buf, math.MaxInt64), VarintBytes(math.MaxInt64))
require.Equal(t, binary.PutVarint(buf, math.MinInt64), VarintBytes(math.MinInt64))
}

0 comments on commit af02562

Please sign in to comment.