1// Copyright (C) 2019 Storj Labs, Inc.
2// See LICENSE for copying information.
3
4package drpcwire
5
6import (
7	"testing"
8
9	"github.com/zeebo/assert"
10)
11
12func TestVarint(t *testing.T) {
13	t.Run("Round Trip", func(t *testing.T) {
14		for i := 0; i < 64; i++ {
15			// val has i+1 lower bits set
16			val := (uint64(1) << uint(i+1)) - 1
17
18			// the encoding should be related to the number of bits set
19			buf := AppendVarint(nil, val)
20			assert.Equal(t, (i/7)+1, len(buf))
21
22			// it should decode to the same value
23			gotBuf, gotVal, ok, err := ReadVarint(buf)
24			assert.NoError(t, err)
25			assert.That(t, ok)
26			assert.Equal(t, 0, len(gotBuf))
27			assert.Equal(t, val, gotVal)
28		}
29	})
30
31	t.Run("Round Trip Fuzz", func(t *testing.T) {
32		for i := 0; i < 10000; i++ {
33			val := RandUint64()
34			buf := AppendVarint(nil, val)
35			gotBuf, gotVal, ok, err := ReadVarint(buf)
36			assert.NoError(t, err)
37			assert.That(t, ok)
38			assert.Equal(t, 0, len(gotBuf))
39			assert.Equal(t, val, gotVal)
40		}
41	})
42}
43