1
2
3
4
5 package catmsg
6
7 import (
8 "fmt"
9 "testing"
10 )
11
12 func TestEncodeUint(t *testing.T) {
13 testCases := []struct {
14 x uint64
15 enc string
16 }{
17 {0, "\x00"},
18 {1, "\x01"},
19 {2, "\x02"},
20 {0x7f, "\x7f"},
21 {0x80, "\x80\x01"},
22 {1 << 14, "\x80\x80\x01"},
23 {0xffffffff, "\xff\xff\xff\xff\x0f"},
24 {0xffffffffffffffff, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01"},
25 }
26 for _, tc := range testCases {
27 buf := [maxVarintBytes]byte{}
28 got := string(buf[:encodeUint(buf[:], tc.x)])
29 if got != tc.enc {
30 t.Errorf("EncodeUint(%#x) = %q; want %q", tc.x, got, tc.enc)
31 }
32 }
33 }
34
35 func TestDecodeUint(t *testing.T) {
36 testCases := []struct {
37 x uint64
38 size int
39 enc string
40 err error
41 }{{
42 x: 0,
43 size: 0,
44 enc: "",
45 err: errIllegalVarint,
46 }, {
47 x: 0,
48 size: 1,
49 enc: "\x80",
50 err: errIllegalVarint,
51 }, {
52 x: 0,
53 size: 3,
54 enc: "\x80\x80\x80",
55 err: errIllegalVarint,
56 }, {
57 x: 0,
58 size: 1,
59 enc: "\x00",
60 }, {
61 x: 1,
62 size: 1,
63 enc: "\x01",
64 }, {
65 x: 2,
66 size: 1,
67 enc: "\x02",
68 }, {
69 x: 0x7f,
70 size: 1,
71 enc: "\x7f",
72 }, {
73 x: 0x80,
74 size: 2,
75 enc: "\x80\x01",
76 }, {
77 x: 1 << 14,
78 size: 3,
79 enc: "\x80\x80\x01",
80 }, {
81 x: 0xffffffff,
82 size: 5,
83 enc: "\xff\xff\xff\xff\x0f",
84 }, {
85 x: 0xffffffffffffffff,
86 size: 10,
87 enc: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01",
88 }, {
89 x: 0xffffffffffffffff,
90 size: 10,
91 enc: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00",
92 }, {
93 x: 0,
94 size: 10,
95 enc: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01",
96 err: errVarintTooLarge,
97 }}
98 forms := []struct {
99 name string
100 decode func(s string) (x uint64, size int, err error)
101 }{
102 {"decode", func(s string) (x uint64, size int, err error) {
103 return decodeUint([]byte(s))
104 }},
105 {"decodeString", decodeUintString},
106 }
107 for _, f := range forms {
108 for _, tc := range testCases {
109 t.Run(fmt.Sprintf("%s:%q", f.name, tc.enc), func(t *testing.T) {
110 x, size, err := f.decode(tc.enc)
111 if err != tc.err {
112 t.Errorf("err = %q; want %q", err, tc.err)
113 }
114 if size != tc.size {
115 t.Errorf("size = %d; want %d", size, tc.size)
116 }
117 if x != tc.x {
118 t.Errorf("decode = %#x; want %#x", x, tc.x)
119 }
120 })
121 }
122 }
123 }
124
View as plain text