varint_test.mx raw
1 package varint
2
3 import (
4 "bytes"
5 "testing"
6 )
7
8 // TestRoundTrip covers the boundary values where the terminal-byte encoding
9 // changes width.
10 func TestRoundTrip(t *testing.T) {
11 vals := []uint64{0, 1, 126, 127, 128, 254, 255, 16383, 16384, 1 << 31, 1 << 62}
12 for _, v := range vals {
13 var buf bytes.Buffer
14 Encode(&buf, v)
15 got, err := Decode(&buf)
16 if err != nil {
17 t.Fatal(err)
18 }
19 if got != v {
20 t.Fatalf("roundtrip: got %d want %d", got, v)
21 }
22 if buf.Len() != 0 {
23 t.Fatalf("Decode left %d bytes", buf.Len())
24 }
25 }
26 }
27
28 // TestStream decodes values written back to back: the reader must stop at the
29 // terminal byte and leave the next value in place.
30 func TestStream(t *testing.T) {
31 var buf bytes.Buffer
32 Encode(&buf, uint64(300))
33 Encode(&buf, uint64(7))
34 a, err := Decode(&buf)
35 if err != nil || a != 300 {
36 t.Fatal("first value")
37 }
38 b, err := Decode(&buf)
39 if err != nil || b != 7 {
40 t.Fatal("second value")
41 }
42 }
43
44 func TestDecodeEmpty(t *testing.T) {
45 var buf bytes.Buffer
46 if _, err := Decode(&buf); err == nil {
47 t.Fatal("Decode of an empty reader should fail")
48 }
49 }
50