Skip to content

Commit 9946570

Browse files
authored
Merge pull request #4 from multiformats/fix/varint-msb
fix: varints are LSB
2 parents 85306a9 + 0aa6889 commit 9946570

File tree

2 files changed

+41
-5
lines changed

2 files changed

+41
-5
lines changed

varint.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,10 @@ func FromUvarint(buf []byte) (uint64, int, error) {
4242
if b < 0x80 {
4343
if i > 9 || i == 9 && b > 1 {
4444
return 0, 0, ErrOverflow
45+
} else if b == 0 && s > 0 {
46+
return 0, 0, ErrNotMinimal
4547
}
4648
return x | uint64(b)<<s, i + 1, nil
47-
} else if b == 0x80 && x == 0 {
48-
return 0, 0, ErrNotMinimal
4949
}
5050
x |= uint64(b&0x7f) << s
5151
s += 7
@@ -73,10 +73,12 @@ func ReadUvarint(r io.ByteReader) (uint64, error) {
7373
if b < 0x80 {
7474
if i > 9 || i == 9 && b > 1 {
7575
return 0, ErrOverflow
76+
} else if b == 0 && s > 0 {
77+
// we should never _finish_ on a 0 byte if we
78+
// have more than one byte.
79+
return 0, ErrNotMinimal
7680
}
7781
return x | uint64(b)<<s, nil
78-
} else if b == 0x80 && x == 0 {
79-
return 0, ErrNotMinimal
8082
}
8183
x |= uint64(b&0x7f) << s
8284
s += 7

varint_test.go

+35-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,16 @@ func checkVarint(t *testing.T, x uint64) {
1515
if size != expected {
1616
t.Fatalf("expected varintsize of %d to be %d, got %d", x, expected, size)
1717
}
18+
xi, n, err := FromUvarint(buf)
19+
if err != nil {
20+
t.Fatal("decoding error", err)
21+
}
22+
if n != size {
23+
t.Fatal("read the wrong size")
24+
}
25+
if xi != x {
26+
t.Fatal("expected a different result")
27+
}
1828
}
1929

2030
func TestVarintSize(t *testing.T) {
@@ -44,7 +54,8 @@ func TestOverflow(t *testing.T) {
4454
}
4555

4656
func TestNotMinimal(t *testing.T) {
47-
i, n, err := FromUvarint([]byte{0x80, 0x01})
57+
varint := []byte{0x81, 0x00}
58+
i, n, err := FromUvarint(varint)
4859
if err != ErrNotMinimal {
4960
t.Error("expected an error")
5061
}
@@ -54,6 +65,29 @@ func TestNotMinimal(t *testing.T) {
5465
if i != 0 {
5566
t.Error("expected i = 0")
5667
}
68+
i, n = binary.Uvarint(varint)
69+
if n != len(varint) {
70+
t.Error("expected to read entire buffer")
71+
}
72+
if i != 1 {
73+
t.Error("expected varint 1")
74+
}
75+
}
76+
77+
func TestNotMinimalRead(t *testing.T) {
78+
varint := bytes.NewBuffer([]byte{0x81, 0x00})
79+
i, err := ReadUvarint(varint)
80+
if err != ErrNotMinimal {
81+
t.Error("expected an error")
82+
}
83+
if i != 0 {
84+
t.Error("expected i = 0")
85+
}
86+
varint = bytes.NewBuffer([]byte{0x81, 0x00})
87+
i, err = binary.ReadUvarint(varint)
88+
if i != 1 {
89+
t.Error("expected varint 1")
90+
}
5791
}
5892

5993
func TestUnderflow(t *testing.T) {

0 commit comments

Comments
 (0)